-
Notifications
You must be signed in to change notification settings - Fork 351
/
App Dev: Storing Application Data in Cloud Datastore - Python
99 lines (57 loc) · 2.13 KB
/
App Dev: Storing Application Data in Cloud Datastore - Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// code has been updated make sure to rake region name : ----
|
|
export REGION=<----------------------------------------------| [IN TASK 4 YOU WILL FIND THE REGION]
gcloud auth list
virtualenv -p python3 vrenv
source vrenv/bin/activate
git clone https://github.com/GoogleCloudPlatform/training-data-analyst
cd ~/training-data-analyst/courses/developingapps/python/datastore/start
export GCLOUD_PROJECT=$DEVSHELL_PROJECT_ID
pip install -r requirements.txt
gcloud app create --region "$REGION"
cd quiz/gcp
cat > datastore.py <<EOF_END
# TODO: Import the os module
import os
# END TODO
# TODO: Get the GCLOUD_PROJECT environment variable
project_id = os.getenv('GCLOUD_PROJECT')
# END TODO
from flask import current_app
# TODO: Import the datastore module from the google.cloud package
from google.cloud import datastore
# END TODO
# TODO: Create a Cloud Datastore client object
# The datastore client object requires the Project ID.
# Pass through the Project ID you looked up from the
# environment variable earlier
datastore_client = datastore.Client(project_id)
# END TODO
"""
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):
# TODO: Create a key for a Datastore entity
# whose kind is Question
key = datastore_client.key('Question')
# END TODO
# TODO: Create a Datastore entity object using the key
q_entity = datastore.Entity(key=key)
# END TODO
# TODO: Iterate over the form values supplied to the function
for q_prop, q_val in question.items():
# END TODO
# TODO: Assign each key and value to the Datastore entity
q_entity[q_prop] = q_val
# END TODO
# TODO: Save the entity
datastore_client.put(q_entity)
# END TODO
EOF_END
cd ~/training-data-analyst/courses/developingapps/python/datastore/start
python run_server.py