Setup/Access Datastore From External Server (Python)

Jun 4, 2019
Create datastore.Client from service account json

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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.