Site icon Learning & Doing

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

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

Task 3. Examine the Quiz application code

Review the Flask Web application

Task 4. Adding entities to Cloud Datastore

Create an App Engine application to provision Cloud Datastore

gcloud app create --region "us-central"

Import and use the Python Datastore module

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

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

python run_server.py

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):
    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

python run_server.py

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.

Exit mobile version