如何在Python3中获取带范围的OAuth2.0 access_token

时间:2019-05-30 01:11:58

标签: python python-3.x google-app-engine oauth-2.0 google-cloud-datastore

我有一个将用户数据存储在GCP数据存储中的应用。 我做了一个cron作业,计划使用给定的here指令导出数据存储中的数据。

但是,我需要将python2更改为python3。

根据docs,app使用app_identity库获取令牌。

    from google.appengine.api import app_identity
    access_token, _ = app_identity.get_access_token('https://www.googleapis.com/auth/datastore')

但是根据here,python3不支持该库。

如何在python3中获取access_token?

1 个答案:

答案 0 :(得分:1)

检出google-api-python-client库。 python 3支持该功能,可轻松构建针对Cloud Datastore API的请求。

您还需要更改的另一件事是webapp2库,因为Python 3也不支持该库。您可以使用Flask之类的库替换它。

这是为python 3重写的应用程序的示例。

app.yaml

runtime: python37

handlers:
- url: /.*
  script: auto

(如果需要,service: service_name可以部署到非默认服务)

requirements.txt

Flask
google-api-python-client

main.py

import datetime
import os
from googleapiclient.discovery import build

from flask import Flask, render_template, request

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello, World!'    

@app.route('/cloud-datastore-export')
def export():
    # Deny if not from the Cron Service
    assert request.headers['X-Appengine-Cron']
    # Deny if output_url_prefix not set correctly
    output_url_prefix = request.args.get('output_url_prefix')
    assert output_url_prefix and output_url_prefix.startswith('gs://')
    timestamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
    if '/' not in output_url_prefix[5:]:
      # Only a bucket name has been provided - no prefix or trailing slash
      output_url_prefix += '/' + timestamp
    else:
      output_url_prefix += timestamp
    kinds = request.args.getlist('kind')
    namespace_ids = request.args.getlist('namespace_id')
    entity_filter = {
        'kinds': kinds,
        'namespace_ids': namespace_ids 
    }
    body = {
        'output_url_prefix': output_url_prefix,
        'entity_filter': entity_filter
    }
    project_id = os.environ.get('GOOGLE_CLOUD_PROJECT')
    client = build('datastore', 'v1')
    client.projects().export(projectId=project_id, body=body).execute()  
    return 'Operation started' 


if __name__ == '__main__':
    # This is used when running locally only. When deploying to Google App
    # Engine, a webserver process such as Gunicorn will serve the app. This
    # can be configured by adding an `entrypoint` to app.yaml.
    # Flask's development server will automatically serve static files in
    # the "static" directory. See:
    # http://flask.pocoo.org/docs/1.0/quickstart/#static-files. Once deployed,
    # App Engine itself will serve those files as configured in app.yaml.
    app.run(host='127.0.0.1', port=8080, debug=True)