Python 3.x 如何运行GooglePeople服务内置服务器制作token.pickle

Python 3.x 如何运行GooglePeople服务内置服务器制作token.pickle,python-3.x,flask,service,flow,google-people-api,Python 3.x,Flask,Service,Flow,Google People Api,我尝试制作微型服务器来连接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 conn

我尝试制作微型服务器来连接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

代码使谷歌联系

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', 'v1', 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", first_name, last_name)
    except Exception as e:
        print('khong ghi duoc danh ba',first_name,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
但是我不知道如何在web brower中打开此链接???

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

@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

您好,您是否尝试过在本地计算机上运行OAuth并通过ssh发送令牌?谢谢,我找到了这样做的方法:)我已经升级了解决方案