Checkpoints
Create an App Engine application
/ 50
Create a Cloud Datastore entity
/ 50
App Dev: Storing Application Data in Cloud Datastore - Python
GSP184
Overview
Google Cloud Datastore is a NoSQL document database built for automatic scaling, high performance, and ease of application development. In this lab, you use Datastore to store application data for an online Quiz application. You also configure the application to retrieve from Datastore and display the data in the quiz.
The Quiz application skeleton has already been written. You clone the repository that contains the skeleton using Google Cloud Shell, review the code using the Cloud Shell editor, and view it using the Cloud Shell web preview feature. You then modify the code that stores data to use Cloud Datastore.
Objectives
In this lab, you learn how to perform the following tasks:
-
Harness Cloud Shell as your development environment
-
Preview the application
-
Update the application code to integrate Cloud Datastore
Setup and requirements
Before you click the Start Lab button
Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.
This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.
To complete this lab, you need:
- Access to a standard internet browser (Chrome browser recommended).
- Time to complete the lab---remember, once you start, you cannot pause a lab.
How to start your lab and sign in to the Google Cloud Console
-
Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:
- The Open Google Console button
- Time remaining
- The temporary credentials that you must use for this lab
- Other information, if needed, to step through this lab
-
Click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page.
Tip: Arrange the tabs in separate windows, side-by-side.
Note: If you see the Choose an account dialog, click Use Another Account. -
If necessary, copy the Username from the Lab Details panel and paste it into the Sign in dialog. Click Next.
-
Copy the Password from the Lab Details panel and paste it into the Welcome dialog. Click Next.
Important: You must use the credentials from the left panel. Do not use your Google Cloud Skills Boost credentials. Note: Using your own Google Cloud account for this lab may incur extra charges. -
Click through the subsequent pages:
- Accept the terms and conditions.
- Do not add recovery options or two-factor authentication (because this is a temporary account).
- Do not sign up for free trials.
After a few moments, the Cloud Console opens in this tab.
Activate Cloud Shell
Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.
- In the Cloud Console, in the top right toolbar, click the Activate Cloud Shell button.
- Click Continue.
It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. The output contains a line that declares the PROJECT_ID for this session:
gcloud
is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.
-
(Optional) You can list the active account name with this command:
(Output)
-
(Optional) You can list the project ID with this command:
(Output)
(Example output)
gcloud
, in Google Cloud, Cloud SDK documentation, see the gcloud command-line tool overview.
Launch the Cloud Shell code editor
From Cloud Shell, click the Open Editor icon to launch the code editor. You may need to click on Open In New Window.
Create a virtual environment
Click on the Open Terminal icon.
Python virtual environments are used to isolate package installation from the system.
Activate the virtual environment
Prepare the Quiz application
The repository containing the Quiz application is located on GitHub.com
.
In this section, you use Cloud Shell to enter commands that clone the repository and run the application.
Clone source code in Cloud Shell
Clone the repository for the class:
Configure and run the Quiz application
-
Change the working directory:
-
Export an environment variable,
GCLOUD_PROJECT
that references the Project ID:export GCLOUD_PROJECT=$DEVSHELL_PROJECT_ID -
Install the application dependencies:
pip install -r requirements.txt Ignore the incompatibility warnings.
-
Run the application:
python run_server.py The application is running When you see a message similar to the following:
* Running on http://127.0.0.1:8080/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 179-313-240
Review the Quiz application
-
In Cloud Shell, click Web preview > Preview on port 8080 to preview the quiz application.
You should see the user interface for the web application. The three main parts to the application are:
- Create Question
- Take Test
- Leaderboard
-
In the navigation bar, click Create Question.
You should see a simple form that contains textboxes for the question and answers with radio buttons to select the correct answer.
-
In the navigation bar, click Take Test, and then GCP to access the Google Cloud questions.
You should see a sample question.
Quiz takers answer questions in this part of the application.
-
To return to the server-side application, click on the Quite Interesting Quiz link in the navigation bar.
Examine the Quiz Application Code
In this lab, you'll view and edit files. You can use the shell editors that are installed on Cloud Shell, such as nano
or vim
or the Cloud Shell code editor.
This lab uses the Cloud Shell code editor to review the Quiz application code.
Review the Flask Web application
-
Navigate to the
/training-data-analyst/courses/developingapps/python/datastore/start
folder using the file browser panel on the left side of the editor. -
Select the
...run_server.py
file.This file contains the entrypoint for the application, and runs it on port 8080.
-
Select the
...quiz/_init_.py file
.This file imports routes for the web application and REST API.
-
Select the
...quiz/webapp/questions.py
and...quiz/webapp/routes.py
file.These files contain the routes that map URIs to handlers that display the form and collect form data posted by quiz authors in the web application.
-
Select the
...quiz/webapp/templates
folder.This folder contains templates for the web application user interface using Jinja2 templates.
-
View the
...quiz/webapp/templates/add.html
file.This file contains the Jinja2 template for the Create Question form.
Notice how there is a select list to pick a quiz, textboxes where an author can enter the question and answers, and radio buttons to select the correct answer.
-
Select the
...quiz/api/api.py
file.This file contains the handler that sends JSON data to students taking a test.
-
Select the
...quiz/gcp/datastore.py
file.This is the file where you write Datastore code to save and load quiz questions to and from Cloud Datastore.
This module will be imported into the web application and API.
Adding Entities to Cloud Datastore
In this section, you write code to save form data in Cloud Datastore.
Create an App Engine application to provision Cloud Datastore
-
Return to Cloud Shell and stop the application by pressing Ctrl+c.
-
To create an App Engine application in your project:
gcloud app create --region "us-central"
You'll see this message when the App Engine has been created:
Note: You aren't using App Engine for your web application yet. However, Cloud Datastore requires you to create an App Engine application in your project.
Click Check my progress below to check your lab progress.
Import and use the Python Datastore module
Open the ...quiz/gcp/datastore.py
file in the Cloud Shell editor and add the following code to perform the following:
- Import the
os
module. - Use the os module to get the
GCLOUD_PROJECT
environment variable. - Import the
datastore
module from thegoogle.cloud
package. - Declare a
datastore.Client
client object nameddatastore_client
.
Updated datastore.py
Write code to create a Cloud Datastore entity
Still in ...quiz/gcp/datastore.py
,
Move to the save_question()
function and remove the existing pass
placeholder statement. Add the following code to perform the following:
- Use the Datastore client object to create a key for a Datastore entity whose kind is
'Question'
. - Use Datastore to create a Datastore question entity with the key.
- Iterate over the items in the dictionary of values supplied from the Web application form.
- In the body of the loop, assign each key and value to the Datastore entity object.
- Use the Datastore client to save the data.
datastore.py - save_question() function
Save datastore.py
.
Run the application and create a Cloud Datastore entity
-
Save the
...quiz/gcp/datastore.py
file and then return to the Cloud Shell command prompt. -
To run the application, execute the following command:
- In Cloud Shell, click Web preview > Preview on port 8080 to preview the quiz application.
- Click Create Question.
- Complete the form with the following values, and then click Save.
Form Field |
Value |
Author |
|
Quiz |
|
Title |
|
Answer 1 |
|
Answer 2 |
|
Answer 3 |
|
Answer 4 |
|
You should return to the application home page.
- Return to the Console, click Navigation menu > Datastore > Entities.
You should see your new question!
Click Check my progress below to check your lab progress.
Retrieve Cloud Datastore entities
In this section, you write code to retrieve entity data from Cloud Datastore to view your question in the application.
Write code to retrieve Cloud Datastore entities
In the code editor, in the ...quiz/gcp/datastore.py
file, remove the code for the list_entities(quiz, redact)
function and replace it with a query that:
- Retrieves Question entities for a specific quiz from Cloud Datastore.
- Uses the Datastore client to fetch the query, and uses the returned data to create a list.
- Enumerate the list of items, and promote each entity's Key identifier to a top level property.
- Return the results.
Replace this code:
With this code:
Save datastore.py
.
Run the application and test the Cloud Datastore query
Now to test if your question is retrieved from Datastore and loaded into your Quiz application.
In Cloud Shell, press Ctrl+c to stop the application, then restart the application:
Preview the quiz: If the browser running the quiz is still open, reload the browser. Otherwise, click Web preview > Preview on port 8080.
Click Take Test > GCP.
You should see the questions you created.
Congratulations!
This concludes the self-paced lab, App Dev: Storing Application Data in Cloud Datastore - Python. You used Datastore to store application data for an online Quiz application. You also configured the application to retrieve and display the data in the quiz.
Finish your Quest
This self-paced lab is part of the Application Development - Python and Cloud Development Quests. A Quest is a series of related labs that form a learning path. Completing this Quest earns you the badge above, to recognize your achievement. You can make your badge (or badges) public and link to them in your online resume or social media account. Enroll in this Quest and get immediate completion credit if you've taken this lab. See other available Quests.
Next steps / learn more
-
For more information about Datastore, see Google Cloud Datastore Documentation.
-
Learn more about Python on the Google Cloud.
Manual last updated January 14, 2022
Lab last tested January 14, 2022
Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.