Skip to content

Instantly share code, notes, and snippets.

@mieitza
Forked from bluemyria/1_quiz_gcp_datastore.py
Created May 16, 2023 15:15
Show Gist options
  • Save mieitza/4bc9f7eb5872b61fe9b026d12ea86731 to your computer and use it in GitHub Desktop.
Save mieitza/4bc9f7eb5872b61fe9b026d12ea86731 to your computer and use it in GitHub Desktop.
GCP Dev: 2. Storing Application Data in Cloud Datastore - Python
# Import the os module
import os
# Use the os module to get the GCLOUD_PROJECT environment variable
project_id = os.getenv('GCLOUD_PROJECT')
from flask import current_app
# Import the datastore module from the google.cloud package.
from google.cloud import datastore
# Declare a datastore.Client client object named datastore_client
datastore_client = datastore.Client(project_id)
"""
Create and persist and entity for each question
The Datastore key is the equivalent of a primary key in a relational database.
There are two main ways of writing a key:
1. Specify the kind, and let Datastore generate a unique numeric id
2. Specify the kind and a unique string id
"""
def save_question(question):
# Create a key for a Datastore entity whose kind is Question
key = datastore_client.key('Question')
# Create a Datastore entity object using the key
q_entity = datastore.Entity(key=key)
# Iterate over the form values supplied to the function
# & Assign each key and value to the Datastore entity
for q_prop, q_val in question.iteritems():
q_entity[q_prop] = q_val
# Save the entity
datastore_client.put(q_entity)
# Write code to retrieve Cloud Datastore entities
"""
Returns a list of question entities for a given quiz
- filter by quiz name, defaulting to gcp
- no paging
- add in the entity key as the id property
- if redact is true, remove the correctAnswer property from each entity
"""
def list_entities(quiz='gcp', redact=True):
query = datastore_client.query(kind='Question')
query.add_filter('quiz', '=', quiz)
results = list(query.fetch())
for result in results:
result['id'] = result.key.id
if redact:
for result in results:
del result['correctAnswer']
return results
cd ~/training-data-analyst/courses/developingapps/python/datastore/start
export GCLOUD_PROJECT=$DEVSHELL_PROJECT_ID
sudo pip install -r requirements.txt
python run_server.py
# Web preview > Preview on port 8080
# from GCP Console: Launch the code editor icon (looks like a pencil)
# Adding Entities to Cloud Datastore (form data of the quiz app)
# Create an App Engine application to provision Cloud Datastore
gcloud app create --region "us-central"
# (You aren't using App Engine for your web application yet.
# but Cloud Datastore requires you to create an App Engine application in your project.)
# after updating quiz_gcp_datastore.py
python run_server.py
# Web preview > Preview on port 8080
# Navigation menu > Datastore > Entities
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment