Search code examples
python-3.xgoogle-cloud-platformgoogle-cloud-datastore

How to connect Google Datastore from a script in Python 3


We want to do some stuff with the data that is in the Google Datastore. We have a database already, We would like to use Python 3 to handle the data and make queries from a script on our developing machines. Which would be the easiest way to accomplish what we need?


Solution

  • From the 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.