Friday, November 15, 2024
Cloud Datastore GCP Juara GCP Python

App Dev: Storing Application Data in Cloud Datastore – Python

storing

“App Dev: Storing Application Data in Cloud Datastore – Python”

Pengantar

Google Cloud Datastore adalah database dokumen NoSQL yang dibuat untuk penskalaan otomatis, performa tinggi, dan kemudahan pengembangan aplikasi. Di lab ini, Anda menggunakan Datastore untuk menyimpan data aplikasi untuk aplikasi Kuis online. Anda juga mengonfigurasi aplikasi untuk mengambil dari Datastore dan menampilkan data dalam kuis.

Kerangka aplikasi Kuis telah ditulis. Anda menggandakan repositori yang berisi kerangka menggunakan Google Cloud Shell, meninjau kode menggunakan editor Cloud Shell, dan melihatnya menggunakan fitur pratinjau web Cloud Shell. Anda kemudian mengubah kode yang menyimpan data untuk menggunakan Cloud Datastore.

Praktikum

Task 1. Create a virtual environment

virtualenv -p python3 vrenv
source vrenv/bin/activate

Task 2. Prepare the Quiz application

Clone source code in Cloud Shell

git clone https://github.com/GoogleCloudPlatform/training-data-analyst

Configure and run the Quiz application

  • Change the working directory:
cd ~/training-data-analyst/courses/developingapps/python/datastore/start
export GCLOUD_PROJECT=$DEVSHELL_PROJECT_ID
pip install -r requirements.txt
python run_server.py

Review the Quiz application

  • In Cloud Shell, click Web preview > Preview on port 8080 to preview the quiz application.

Task 3. Examine the Quiz application code

Review the Flask Web application

  • 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.
Baca Juga :  App Dev: Deploying the Application into Kubernetes Engine - Python

Task 4. Adding entities to 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, use:
gcloud app create --region "us-central"

Import and use the Python Datastore module

  • Open the ...quiz/gcp/datastore.py file in the Cloud Shell editor and add the Updated datastore.py code listed below to perform the following:
  • Import the os module.
  • Use the os module to get the GCLOUD_PROJECT environment variable.
  • Import the datastore module from the google.cloud package.
  • Declare a datastore.Client client object named datastore_client.

Updated datastore.py

# 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

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 datastore.py – save_question() function code listed below 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.
Baca Juga :  Cloud KMS

datastore.py – save_question() function

"""
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

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:
python run_server.py
  • 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.
  • Return to the Console, click Navigation menu > Datastore > Entities.

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:
"""
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):
    return [{'quiz':'gcp', 'title':'Sample question', 'answer1': 'A', 'answer2': 'B', 'answer3': 'C', 'answer4': 'D', 'correctAnswer': 1, 'author': 'Nigel'}]
"""

With this code:

"""
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
"""

Run the application and test the Cloud Datastore query

  • In Cloud Shell, press Ctrl+c to stop the application, then restart the application:
python run_server.py
  • 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
Baca Juga :  Reduce Costs for the Managed Service for Prometheus

Penutup

Sahabat Blog Learning & Doing demikianlah penjelasan mengenai App Dev: Storing Application Data in Cloud Datastore – Python. Semoga Bermanfaat . Sampai ketemu lagi di postingan berikut nya.

(Visited 82 times, 1 visits today)

Similar Posts