Python Datastore CRUD NoSQL
Enable APIS and SERVICES
Click Enable
Select Datastore on left hand side
Note: You can pin any selection so it will remain on the top of the menu
Click into Datastore
Create a Datastore Table to store customer name, address and instructions
Hit Create Entity
In the Kind text box type Custinfo
In the Key identifier click custom name
In Custom name box type name
Click on ADD PROPERTY
In New Property Name* type in Address with type string
Click on ADD PROPERTY again
In New Property Name* type in address_type with type text
Click on ADD PROPERTY again
In New Property Name* type in instructions with type text
Click on Create
The Datastore table in now ready to have data loaded to it
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. When called, it returns a response object and redirects the user to another target location with specific status code. location parameter is the URL where response should be redirected. status code sent to browser's header, defaults to 302.
Access your linux shell to enter command mode by clicking >- sign
Welcome to Cloud Shell! Type "help" to get started.
Your Cloud Platform project in this session is set to uconn-engr.
Use “gcloud config set project [PROJECT_ID]” to change to a different project.
john_iacovacci1@cloudshell:~ (uconn-engr)$
Next we create a directory to store you app engine code (python, html and css)
john_iacovacci1@cloudshell:~ (uconn-engr)$ mkdir uconn-datastore
Directory structure example
Now change into the directory you want to place your code in
john_iacovacci1@cloudshell:~ (uconn-engr)$ cd uconn-datastore
john_iacovacci1@cloudshell:~/uconn-datastore (uconn-engr)$
Now open editor
Highlight the directory uconn-datastore
Open a New File
Call it main.py
Paste code below
=========================================================
Code for main main.py
=========================================================
# Required Flask Libraries
from flask import Flask, request, render_template, redirect, send_from_directory
from google.cloud import translate_v2 as translate
translate_client = translate.Client()
# Imports the Google Cloud client library
from google.cloud import datastore
# START Translate requirements
#from google.cloud import translate
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'],
'address_type': data['address_type']
})
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'], address_type=customer['address_type'])
# 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']
customer['address_type'] = data['address_type']
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'], address_type=customer['address_type'])
# 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('/')
# Don't worry about this part
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
===========================================================
Make a directory under uconn-datastore called templates
Then create a file called index.html under the templates directory
Note: The library Flask requires that html be placed in a directory called templates
under your project folder
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
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_type">Address Type</label>
<select class="form-control" id="address_type" name="address_type">
<option value="personal" selected>Personal</option>
<option value="commercial">Commercial</option>
</select>
</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>
=========================================================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>
Address Type: {{ address_type }} <br>
Instructions: {{ instructions }} <br>
Translated : {{ transinstructions }}
</section>
</body>
</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_type">Address Type</label>
<select class="form-control" id="address_type" name="address_type">
<option value="personal" {% if address_type == "personal" %}selected{% endif %}>Personal</option>
<option value="commercial" {% if address_type == "commercial" %}selected{% endif %}>Commercial</option>
</select>
</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 uconn-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 uconn-datastore directory
app.yaml
===========================================================
runtime: python38
===========================================================
requirements.txt
===============================================================
google-cloud-datastore
Google-cloud-translate
===============================================================
Make sure you save all then back to terminal
From your uconn-datastore directory deploy the app
john_iacovacci1@cloudshell:~/uconn-datastore (uconn-engr)$ gcloud app deploy
Services to deploy:
descriptor: [/home/john_iacovacci1/uconn-datastore/app.yaml]
source: [/home/john_iacovacci1/uconn-datastore]
target project: [uconn-engr]
target service: [default]
target version: [20210227t174130]
target url: [https://uconn-engr.uc.r.appspot.com]
Do you want to continue (Y/n)?
Beginning deployment of service [default]...
Created .gcloudignore file. See `gcloud topic gcloudignore` for details.
╔════════════════════════════════════════════════════════════╗
╠═ Uploading 6 files to Google Cloud Storage ═╣
╚════════════════════════════════════════════════════════════╝
File upload done.
Updating service [default]...done.
Setting traffic split for service [default]...done.
Deployed service [default] to [https://uconn-engr.uc.r.appspot.com]
You can stream logs from the command line by running:
$ gcloud app logs tail -s default
To view your application in the web browser run:
$ gcloud app browse
Now app is ready for access via app engine dashboard
No comments:
Post a Comment