UCONN

UCONN
UCONN

Assignment Exercise: Python Datastore CRUD NoSQL v2

 Python Datastore CRUD NoSQL

Enable APIS and SERVICES, Search for API & SERVICES


Enable APIs and services

 Search for Google Translate API

Enable Cloud Translation API

Enable Cloud Datastore 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 Address as string, 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 


(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 customer-datastore


Now change into the directory you want to place your code in


john_iacovacci1@cloudshell:~ (cloud-project-examples)$ cd customer-datastore/

john_iacovacci1@cloudshell:~/cust-datastore (cloud-project-examples)$ 


Now open editor



Highlight the customer-datastore folder

then click + file icon to create new file


Enter main.py














Paste code below

=========================================================

Code for main.py 

=========================================================

from flask import Flask, request, render_template, redirect

from google.cloud import datastore, translate_v2 as translate

import os


app = Flask(__name__)

db = datastore.Client()

trans = translate.Client()

KIND = 'Custinfo'


@app.route('/')

def index():

    customers = list(db.query(kind=KIND).fetch())

    return render_template('index.html', customers=customers)


@app.route('/create', methods=['GET', 'POST'])

def create():

    if request.method == 'POST':

        data = request.form.to_dict()

        key = db.key(KIND, data['Name'])

        entity = datastore.Entity(key=key)

        entity.update(data)

        db.put(entity)

        return redirect(f"/read/{data['Name']}")

    return render_template('form.html', customer={})


@app.route('/read/<name>')

def read(name):

    customer = db.get(db.key(KIND, name))

    # Simplify translation call

    res = trans.translate(customer['instructions'], target_language='es')

    return render_template('customer.html', c=customer, translated=res['translatedText'])


@app.route('/update/<name>', methods=['GET', 'POST'])

def update(name):

    key = db.key(KIND, name)

    customer = db.get(key)

    if request.method == 'POST':

        customer.update(request.form.to_dict())

        db.put(customer)

        return redirect(f"/read/{name}")

    return render_template('form.html', customer=customer, update=True)


@app.route('/delete/<name>')

def delete(name):

    db.delete(db.key(KIND, name))

    return redirect('/')


if __name__ == '__main__':

    app.run(host="127.0.0.1", port=8080, debug=True)

=========================================================


Highlight the customer-datastore directory create directorycalled templates

By clicking the icon 


Highlight the templates directory then

Create a file called layout.html by clicking the icon



Note: Flask requires that html be placed in a directory called templates 


templates/layout.html

=========================================================

<!DOCTYPE html>

<html>

<head>

    <title>CRUD Example</title>

    <link rel="stylesheet" href="/static/style.css">

</head>

<body>

    <nav class="navbar">

        <a class="navbar-brand" href="/">Customers</a>

        <a href="/create">Add Customer</a>

    </nav>

    <section>{% block content %}{% endblock %}</section>

</body>

</html>

=========================================================

Now create another file under templates called index.html


templates/index.html

=========================================================

{% extends "layout.html" %}

{% block content %}

<h2>Customers</h2>

<ul>

    {% for c in customers %}

        <li><a href="/read/{{ c.Name }}">{{ c.Name }}</a></li>

    {% else %}

        <li>No customers yet. <a href="/create">Add one</a>.</li>

    {% endfor %}

</ul>

{% endblock %}

=========================================================

Next create a file called form.html

templates/form.html

========================================================

{% extends "layout.html" %}

{% block content %}

<form method="post">

    <label>Name</label>

    <input type="text" name="Name" value="{{ customer.Name or '' }}" {{ 'disabled' if update }}>

    <br><label>Address</label>

    <textarea name="address">{{ customer.address or '' }}</textarea>

    <br><label>Instructions</label>

    <textarea name="instructions">{{ customer.instructions or '' }}</textarea>

    <br><button type="submit">Submit</button>

</form>

{% endblock %}

=========================================================

Last html file needed is customer.html

templates/customer.html

=========================================================

{% extends "layout.html" %}

{% block content %}

    <a href="/update/{{ c.Name }}">Update</a> | <a href="/delete/{{ c.Name }}">Delete</a>

    <hr>

    <p><strong>Name:</strong> {{ c.Name }}</p>

    <p><strong>Address:</strong> {{ c.address }}</p>

    <p><strong>English:</strong> {{ c.instructions }}</p>

    <p><strong>Spanish:</strong> {{ translated }}</p>

{% endblock %}

=========================================================

Now we need to create another directory to hold our style.css file

Create a new folder called static

 

 Highlight the newly created directory

 Create a new file called style.css

 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 customer-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 customer-datastore directory deploy the app

 john_iacovacci1@cloudshell:~/customer-datastore (cloud-project-examples)$ gcloud run deploy python-nosql-crud --source . --allow-unauthenticated --region us-east1

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

Optional Assignment #4

  I created a shorter simpler version for the Python CRUD example for those who were having issues and wish to try it out. https://uconnstam...