我有一个在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?
最佳答案
检出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)
关于python - 如何在Python3中使用App Engine安排Cloud Datastore导出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56370413/