如何在服务器中运行Google People Service构建以制作token.pickle

问题描述

我尝试使微服务器连接Google People API。 我在本地主机“ MACOS”中运行,一切正常。 但是在我部署到服务器“ CENTOS”之后,服务器无法呈现身份验证URL: 使Google服务构建的代码

def contact_service_build(pickle_file_name):
    """Shows basic usage of the People API.
    Prints the name of the first 10 connections.
    """
    path = str(dir.dir)
    token_file = path + '/project/google_auth/'+pickle_file_name+ '.pickle'
    secrets_file = path + '/project/credentials/credentials.json'
    ScopES = ['https://www.googleapis.com/auth/contacts']
    creds = None
    # The file token.pickle stores the user's access and refresh tokens,and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists(token_file):
        with open(token_file,'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available,let the user log in.
    if not creds or not creds.valid:
        print('not creds or not creds.valid')
        if creds and creds.expired and creds.refresh_token:
            print('creds and creds.expired and creds.refresh_token')
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(secrets_file,ScopES)
            creds = flow.run_local_server(port=0)
            print('creds = flow.run_local_server(port=0)')
        # Save the credentials for the next run
        with open(token_file,'wb') as token:
            pickle.dump(creds,token)
    service = build('people','v1',credentials=creds)
    return service

与Google建立联系的代码

def creat_google_contact(service,first_name,last_name,phone,email,streetAddress,extendedAddress,city,zip,province,country,country_code,biographies,company):
    # POST / v1 / people: createContact
    # HTTP / 1.1
    # Body: {"names": [{"givenname": "John","familyName": "Doe"}]}
    # Host: people.googleapis.comcompany
    # service = discovery.build('people',http=http,discoveryServiceUrl='https://people.googleapis.com/$discovery/rest')
    try:
        service.people().createContact(body={
            "organizations": [
                {
                    "name": str(company)
                }
            ],"biographies": [
                {
                    "value": str(biographies),"contentType": 'TEXT_HTML'
                }
            ],"names": [
                {
                    "givenname": str(last_name),"familyName": str(first_name)
                }
            ],"phoneNumbers": [
                {
                    'value': str(phone)
                }
            ],"emailAddresses": [
                {
                    'value': str(email)
                }
            ],"addresses": [
                {
                    "streetAddress": str(streetAddress),"extendedAddress": str(extendedAddress),"city": str(city),"region": str(province),"postalCode": str(zip),"country": str(country),"countryCode": str(country_code)
                }
            ]
        }).execute()
        print("da ghi lenh danh ba gooogle",last_name)
    except Exception as e:
        print('khong ghi duoc danh ba',last_name)
        pass

在SSH终端中,我可以看到python打印出来

127.0.0.1 - - [09/Sep/2020 12:04:30] "GET /sync_contact HTTP/1.0" 200 -
not creds or not creds.valid
Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=44359f0pm.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A36883%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcontacts&state=7mjA48LHGRZnRT&access_type=offline

但是我不知道在网络浏览器中打开此链接方法吗??

解决方法

谢谢大家 经过研究,我找到了解决方法

@contact.route('/sync_authorize')
@login_required
def sync_authorize():
    SCOPES = 'https://www.googleapis.com/auth/userinfo.profile openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/contacts'
      # Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps.
    path = str(dir.dir)
    secrets_file = path + '/project/credentials/credentials.json'
    flow = Flow.from_client_secrets_file(
          secrets_file,scopes=SCOPES)

    flow.redirect_uri = url_for('contact.sync_callback',_external=True)

    authorization_url,state = flow.authorization_url(
          access_type='offline',include_granted_scopes='true')

    flask.session['state'] = state

    return redirect(authorization_url)


@contact.route('/sync_callback')
@login_required
def sync_callback():
    email = current_user.email
    name = email.split('@')[0]
    name = name.split('.')[0]
    path = str(dir.dir)
    token_file = path + '/project/google_auth/' + name + '.pickle'
    print('token_file: ',token_file)
    SCOPES = 'https://www.googleapis.com/auth/userinfo.profile openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/contacts'
    state = flask.session['state']
    secrets_file = path + '/project/credentials/credentials.json'

    credentials = None

    if os.path.exists(token_file):
        with open(token_file,'rb') as token:
            credentials = pickle.load(token)
    else:
        flow = Flow.from_client_secrets_file(
            secrets_file,scopes=SCOPES,state=state)
        flow.redirect_uri = url_for('contact.sync_callback',_external=True)
        # Use the authorization server's response to fetch the OAuth 2.0 tokens.
        authorization_response = request.url
        print('authorization_response',authorization_response)
        flow.fetch_token(authorization_response=authorization_response)
        credentials = flow.credentials
        with open(token_file,'wb') as token:
            pickle.dump(credentials,token)
    service = build('people','v1',credentials=credentials)
-------finish build service-------
CODE TO CREAT DELETE CONTACTS