Python Datastore CRUD NoSQL
Enable APIS and SERVICES
Search for API & SERVICES
Enable APIs and services
Search for Google Translate API
Click on Cloud Translation API
Enable API
Search for Cloud Datastore API
Enable API
Search for Datastore
Create a Firestore database
Provide Database ID and select Standard Edition
Select Firestore with Datastore compatibility, region and us-east1
Then hit Create Database
Create entity
Enter Custinfo in Kind box, key identifier Custom name, Custom name enter name
Add a property for Address as string
Add a prosperity for instructions as text
And hit Create
Datastore ready to load data to in now
We will now build an app engine project based upon python and html code to load data into datastore
Flask class has a redirect() function.
returns a response object
redirects the user to target location
Access your linux shell to enter command mode by clicking >- sign
Welcome to Cloud Shell! Type "help" to get started, or type "gemini" to try prompting with Gemini CLI.
Your Cloud Platform project in this session is set to cloud-project-examples.
Use `gcloud config set project [PROJECT_ID]` to change to a different project.
john_iacovacci1@cloudshell:~ (cloud-project-examples)$
Next we create a directory to store you cloud run code
(python, html and css) and requirements.txt instructions
john_iacovacci1@cloudshell:~ (cloud-project-examples)$ mkdir cust-datastore
Directory structure example
Now change into the directory you want to place your code in
john_iacovacci1@cloudshell:~ (cloud-project-examples)$ cd cust-datastore/
john_iacovacci1@cloudshell:~/cust-datastore (cloud-project-examples)$
Now open editor
Highlight the cust-datastore folder
Highlight the cust-datastore directory
click the + sign to create a new file
Enter main.py
Paste code below
=========================================================
Code for main main.py
=========================================================
# Required Flask Libraries
from flask import Flask, request, render_template, redirect, send_from_directory
import os
port = int(os.environ.get("PORT", 8080))
# Imports the Google Cloud client library
from google.cloud import datastore
# START Translate requirements
from google.cloud import translate_v2 as translate
translate_client = translate.Client()
client = datastore.Client()
kind = 'Custinfo'
# Start Flask app
app = Flask(__name__)
# Index Page retrieves all records in kind and puts them into list for navigation selection
@app.route('/', methods=['GET'])
def index():
# Get Customer List
# retrieves all data with Kind custinfo
query = client.query(kind=kind)
# fetch method that retrieve all results that match query
results = list(query.fetch())
# all data stored in simple list and list is passed thru to the index.html page
return render_template('index.html', customers=results)
# Static directory for css
@app.route('/static/<path:path>')
def send_js(path):
return send_from_directory('static', path)
# CRUD ENDPOINTS
# Create
@app.route('/create', methods=['POST', 'GET'])
def create():
if request.method == 'POST':
data = request.form.to_dict(flat=True) # Data from form
# Put customer record
complete_key = client.key(kind, data['Name'])
customer = datastore.Entity(key=complete_key)
customer.update({
'Name': data['Name'],
'address': data['address'],
'instructions': data['instructions'],
})
client.put(customer)
# Redirect to customer page
return redirect("/read/" + data['Name'])
else:
# GET - Render customer creation form
return render_template('create.html')
# Read
@app.route('/read/<name>', methods=['GET'])
def read(name):
# Retrieve Customer Data
key = client.key(kind, name)
customer = client.get(key)
tinst = customer['instructions']
tlang = 'es'
result = translate_client.translate(tinst, target_language=tlang)
# Render the page
# translate process should go here
return render_template('customer.html', name=customer['Name'], address=customer['address'],
instructions=customer['instructions'], transinstructions=result['translatedText'])
# Update
@app.route('/update/<name>', methods=['GET', 'POST'])
def update(name):
if request.method == 'POST':
data = request.form.to_dict(flat=True) # Data from form
# Update Customer Data
key = client.key(kind, name)
customer = client.get(key)
customer['address'] = data['address']
customer['instructions'] = data['instructions']
client.put(customer)
# Redirect to customer page
return redirect("/read/" + name)
else:
# Get customer data
key = client.key(kind, name)
customer = client.get(key)
# Renders update page with existing data
return render_template('update.html', name=customer['Name'], address=customer['address'],
instructions=customer['instructions'])
# Delete
@app.route('/delete/<name>', methods=['GET'])
def delete(name):
# Delete Customer Record
key = client.key(kind, name)
client.delete(key)
# Redirect to index page
return redirect('/')
if __name__ == '__main__':
app.run(host="127.0.0.1", port=8080, debug=True)
=========================================================
Highlight the cust-datastore directory then
Make a directory under cust-datastore called templates
By clicking the icon
Highlight the templates directory then
Create a file called index.html by clicking the icon
Note: The library Flask requires that html be placed in a directory called templates
Now cut and paste code below
templates/index.html
=========================================================
<!DOCTYPE html>
<html lang="en">
<head>
<title>CRUD Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
{# NavBar #}
<nav class="navbar">
<a class="navbar-brand" href="/">Customers</a>
<a href="/create">Add Customer</a>
</nav>
{# Customer List #}
<section>
<h2>Customers</h2>
<ul>
{# Customer.name is the item in list we display for selection #}
{% for customer in customers %}
<li><a href="/read/{{ customer.Name }}">{{ customer.Name }}</a></li>
{% else %}
<li>You have no customers yet. Click <a href="/create">here</a> or "Add Customer" in the navbar to create one.</li>
{% endfor %}
</ul>
</section>
</body>
</html>
=========================================================
Now create another file under templates called create.html
Cut and paste code below
templates/create.html
=========================================================
<!DOCTYPE html>
<html lang="en">
<head>
<title>CRUD Example - Create Customer</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
{# NavBar #}
<nav class="navbar">
<a class="navbar-brand" href="/">Customers</a>
</nav>
{# Create user form #}
<section>
<form method="post" action="/create">
<div>
<label for="Name">Name</label>
<input type="text" class="form-control" id="Name" name="Name">
<br>
<small class="form-text text-muted">This is the primary key for the customer. It must be unique.</small>
</div>
<br>
<div>
<label for="address">Address</label>
<textarea class="form-control" id="address" name="address" rows="3"></textarea>
</div>
<br>
<div>
<label for="address">Instructions</label>
<textarea class="form-control" id="instructions" name="instructions" rows="5"></textarea>
</div>
<br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</section>
</body>
</html>
=========================================================
Next create a file called customer.html
templates/customer.html
========================================================
<!DOCTYPE html>
<html lang="en">
<head>
<title>CRUD Example - Customer</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
{# NavBar #}
<nav class="navbar">
<a class="navbar-brand" href="/">Customers</a>
<a href="/create">Add Customer</a>
</nav>
{# Customer Options #}
<section>
<div class="container">
<ul>
<li><a href="/update/{{ name }}">Update</a></li>
<li><a href="/delete/{{ name }}">Delete</a></li>
</ul>
</div>
</section>
{# Customer info #}
<section>
Name: {{ name }} <br>
Address: {{ address }} <br>
Instructions: {{ instructions }} <br>
Translated : {{ transinstructions }}
</section>
</body>
</html>
=========================================================
Last html file needed is update.html
templates/update.html
=========================================================
<!DOCTYPE html>
<html lang="en">
<head>
<title>CRUD Example - Update Customer</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
{# NavBar #}
<nav class="navbar">
<a class="navbar-brand" href="/">Customers</a>
<a href="/create">Add Customer</a>
</nav>
{# Update user form #}
<section>
<form method="post" action="/update/{{ name }}">
<div>
<label for="Name">Name</label>
<input type="text" class="form-control" id="Name" name="Name" disabled value="{{ name }}">
<br>
<small class="form-text text-muted">This is the primary key for the customer. It should not be changed.</small>
</div>
<br>
<div>
<label for="address">Address</label>
<textarea class="form-control" id="address" name="address" rows="3">{{address}}</textarea>
</div>
<br>
<div>
<label for="address">Instructions</label>
<textarea class="form-control" id="instructions" name="instructions" rows="5">{{instructions}}</textarea>
</div>
<br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</section>
</body>
</html>
=========================================================
Now we need to create another directory to hold our style.css file
Make sure cust-datastore is highlighted
Create a new folder called static
Highlight the newly created directory
Create a new file called style.css
Cut and paste code below
static/style.css
=========================================================
body {
margin: 0;
}
.navbar {
background-color: #DDDDDD;
margin-bottom: 10px;
padding: 8px;
}
.navbar-brand {
font-size: larger;
}
section {
max-width: 1200px;
margin: auto;
padding: 8px;
}
========================================================
Back up to cust-datastore directory and highlight
And create a file called requirements.txt
========================================================
Flask==3.0.0
google-cloud-datastore
Google-cloud-translate
gunicorn==21.2.0
=======================================================
Go back to Open Terminal
From your cust-datastore directory deploy the app
john_iacovacci1@cloudshell:~/cust-datastore (cloud-project-examples)$ gcloud run deploy python-nosql-crud --source . --allow-unauthenticated --region us-east1
uthenticated --region us-east1
Building using Buildpacks and deploying container to Cloud Run service [python-nosql-crud] in project [cloud-project-examples] region [us-east1]
Building and deploying...
Validating configuration...done
Uploading sources...done
Building Container... Logs are available at [https://console.cloud.google.com/cloud-build/builds;region=us-east1/dfe495f4-db7
2-4603-9bd5-ef4a571861f1?project=517129368909]....done
Setting IAM Policy...done
Creating Revision...done
Routing traffic...done
Done.
Service [python-nosql-crud] revision [python-nosql-crud-00005-pcd] has been deployed and is serving 100 percent of traffic.
Service URL: https://python-nosql-crud-517129368909.us-east1.run.app
john_iacovacci1@cloudshell:~/cust-datastore (cloud-project-examples)$
Now click on the Service URL:
Add Customer
Enter Customer Information
No comments:
Post a Comment