这是一个示例应用,您可以使用 Google App Engine Cron 服务调用它。它基于node.js example in the docs:
app.yaml
runtime: python37
handlers:
- url: /.*
script: auto
如果您已经部署了默认服务,请添加 target: cloud-firestore-admin 以创建新服务。
requirements.txt
Flask
google-api-python-client
google-api-python-client 简化了对 Cloud Firestore REST API 的访问。
main.py
import datetime
import os
from googleapiclient.discovery import build
from flask import Flask, request
app = Flask(__name__)
@app.route('/cloud-firestore-export')
def export():
# Deny if not from the GAE Cron Service
assert request.headers['X-Appengine-Cron']
# Deny if outputUriPrefix not set correctly
outputUriPrefix = request.args.get('outputUriPrefix')
assert outputUriPrefix and outputUriPrefix.startswith('gs://')
# Use a timestamp in export file name
timestamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
if '/' not in outputUriPrefix[5:]:
# Add a trailing slash if missing
outputUriPrefix += '/' + timestamp
else:
outputUriPrefix += timestamp
if 'collections' in request.args:
collections = request.args.get('collections').split(",")
else:
collections = None
body = {
'collectionIds': collections,
'outputUriPrefix': outputUriPrefix,
}
# Build REST API request for
# https://cloud.google.com/firestore/docs/reference/rest/v1/projects.databases/exportDocuments
project_id = os.environ.get('GOOGLE_CLOUD_PROJECT')
database_name = 'projects/{}/databases/(default)'.format(project_id)
service = build('firestore', 'v1')
service.projects().databases().exportDocuments(name=database_name, 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)
cron.yaml
cron:
- description: "Daily Cloud Firestore Export"
url: /cloud-firestore-export?outputUriPrefix=gs://BUCKET_NAME&collections=COLLECTIONS_LIST
schedule: every 24 hours
如果您在 app.yaml 中部署到非默认服务,也请在此处添加:target: cloud-firestore-admin。
App Engine 服务帐户的访问权限
部署后,该应用会使用 GAE 服务帐号来授权导出请求。确保您的 GAE 服务帐号对 Cloud Firestore 和您的存储分区具有权限,请参阅:
https://cloud.google.com/firestore/docs/solutions/schedule-export#configure_access_permissions