如何从 Python 3 中的脚本连接 Google 数据存储

How to connect Google Datastore from a script in Python 3

我们想对 Google 数据存储中的数据做一些事情。我们已经有一个数据库,我们想使用 Python 3 来处理数据并从我们开发机器上的脚本进行查询。哪种方法最容易完成我们的需求?

您可以创建一个服务帐户并将凭据下载为 JSON,然后设置一个名为 GOOGLE_APPLICATION_CREDENTIALS 的环境变量指向 json 文件。您可以在下面的 link 查看详细信息。

https://googleapis.dev/python/google-api-core/latest/auth.html

来自Official Documentation:

  1. You will need to install the Cloud Datastore client library for Python:
pip install --upgrade google-cloud-datastore
  1. Set up authentication by creating a service account and setting an environment variable. It will be easier if you see it, please take a look at the official documentation for more info about this. You can perform this step by either using the GCP console or command line.

  2. Then you will be able to connect to your Cloud Datastore client and use it, as in the example below:

# Imports the Google Cloud client library
from google.cloud import datastore

# Instantiates a client
datastore_client = datastore.Client()

# The kind for the new entity
kind = 'Task'
# The name/ID for the new entity
name = 'sampletask1'
# The Cloud Datastore key for the new entity
task_key = datastore_client.key(kind, name)

# Prepares the new entity
task = datastore.Entity(key=task_key)
task['description'] = 'Buy milk'

# Saves the entity
datastore_client.put(task)

print('Saved {}: {}'.format(task.key.name, task['description']))

As @JohnHanley mentioned, you will find a good example on this Bookshelf app tutorial that uses Cloud Datastore to store its persistent data and metadata for books.