Create Service Account
Option 1: Download App Engine default service account
Access Google Cloud Console -> Service accounts.
Select [email protected] / App Engine default service account
, click on the 3-vertical dots of Actions
and select Create key
. Select JSON
for Key type
the click Create
. Save the JSON file PROJECT_ID-appengine.json
.
NOTE: This key have access to all App Engine resources, so be extra careful with it.
Option 2: Create Datastore only service account key
Access Google Cloud Console -> Create service account key.
- Service account: New service account
- Service account name: datastore
- Role: Datastore -> Cloud Datastore User or Owner
- Key type: JSON
Click create. Save the JSON file PROJECT_ID-datastore.json
.
NOTE: Refer Accessing Datastore from another platform.
Python Datastore Query
from google.cloud import datastorefrom app import logdef init_datastore(): # export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json" # return datastore.Client() return datastore.Client.from_service_account_json('PROJECT_ID-datastore.json')db = init_datastore()query = db.query(kind='Item')query.add_filter('is_active', '=', True)items = query.fetch()for _item in items: log.info(f"name={_item['name']}")
References:
- https://cloud.google.com/datastore/docs/activate#other-platforms
- https://cloud.google.com/docs/authentication/production
- https://cloud.google.com/datastore/docs/datastore-api-tutorial
- https://cloud.google.com/datastore/docs/reference/libraries
- https://googleapis.github.io/google-cloud-python/latest/datastore/index.html
- https://googleapis.github.io/google-cloud-python/