App Engine Hello World Explained


from flask import Flask

# If `entrypoint` is not defined in app.yaml,

App Engine will look for an app

# called `app` in `main.py`.

app = Flask(__name__)

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

def hello():

    """Return a friendly HTTP greeting."""

    return 'Hello UCONN from John Iacovacci!\n'

if __name__ == '__main__':

    # Used when running locally only. When deploying to

Google App

    # Engine, a webserver process such as Gunicorn

will serve the app.

This

    # can be configured by adding an `entrypoint`

to app.yaml.

    app.run(host='localhost', port=8080, debug=True)

 

 

main__ — Top-level script environment


https://docs.python.org/3/library/__main__.html#module-__main__


'__main__' is the name of the scope in which top-level code executes. 

 

A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an

interactive prompt.

 

A module can discover whether or not it is running in the main

scope by checking its own __name__, which allows a common idiom for conditionally executing code

in a module when it is run as a script or with python -m but not when it is imported:

 

if __name__ == "__main__":

    # execute only if run as a script

    main()

 

For a package, the same effect can be achieved by including a__main__.py module, the contents of which will be executed when the

module is run with -m.

 

__name__ is a built-in variable which evaluates to the name

of the current module. Thus it can be used to check whether the current script is

being run on its own or being imported somewhere else by

combining it with if statement, as shown below.

Consider two separate files File1 and File2.

# File1.py

print "File1 __name__ = %s" %__name__

if __name__ == "__main__":

    print "File1 is being run directly"

else:

    print "File1 is being imported"


Flask

Flask is a lightweight WSGI web application framework.

It is designed to make getting started quick and easy,

with the ability to scale up to complex applications.

It began as a simple wrapper around Werkzeug and Jinja

and has become one of the most popular Python web

application frameworks.

Flask offers suggestions, but doesn't enforce any

dependencies or project layout. It is up to the developer

to choose the tools and libraries they want to use.

There are many extensions provided by the community that

make adding new functionality easy.

A web framework (WF) or web application framework

(WAF)is a software framework that is designed to support

the development of web applications including web

services, web resources, and web APIs.

Python code in one module gains access to the code

in another module by the process of importing it.

The import statement is the most common way of

invoking the import machinery Routing is the mechanism

of mapping the URL directly to the code that creates the

webpage.

Use the route() decorator to bind a function to a URL.

app.route(rule, options)

  • The rule parameter represents URL binding with the function.


  • The options is a list of parameters to be forwarded to the underlying Rule object.

Http protocol is the foundation of data communication in world wide web. Different

methods of data retrieval from specified URL are defined in this protocol.

What is HTTP?

The Hypertext Transfer Protocol (HTTP) is designed to enable communications between

clients and servers.

HTTP works as a request-response protocol between a client and server.

Example: A client (browser) sends an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.

HTTP Methods

  • GET

  • POST

  • PUT

  • HEAD

  • DELETE

  • PATCH

  • OPTIONS

The two most common HTTP methods are: GET and POST.

The GET Method

GET is used to request data from a specified resource.

GET is one of the most common HTTP methods.

Note that the query string (name/value pairs) is sent

in the URL of a GET request:

/test/demo_form.php?name1=value1&name2=value2

GET - Sends data in unencrypted form to the server.

Most common method.

The POST Method

POST is used to send data to a server to create/update a resource.

The data sent to the server with POST is stored in the

request body of the HTTP request:

POST /test/demo_form.php HTTP/1.1

Host: w3schools.com

name1=value1&name2=value2

POST is one of the most common HTTP methods.

Some other notes on POST requests:

  • POST requests are never cached

  • POST requests do not remain in the browser history

  • POST requests cannot be bookmarked

  • POST requests have no restrictions on data length

POST - Used to send HTML form data to serve

Web applications use different HTTP methods when accessing

URLs. You should familiarize yourself with the HTTP methods

as you work with Flask. By default, a route only answers

to GET requests. You can use the methods argument of

the route() decorator to handle different HTTP methods.

Finally the run() method of Flask class runs the application

on the local development server.

app.run(host, port, debug, options)

In computer networking, localhost

is a hostname that refers to the current computer used to

access it. It is used to access the network services that

are running on the host via the loopback network interface.

Port 80 is HTTP. Port 443 is HTTPS. Port 8080 is a non-standard,

high number port that is popular as an alternative port for HTTP

servers, most often application servers 

requirements.txt

requirements.txtfile is used for specifying what python packages are required

to run the project you are looking at. 

 

app.yaml file. This configuration file defines your web app's settings

for App Engine.

You configure your App Engine app's settings in the app.yaml

file. The app.yaml file also contains information about your app's

code, Node.js runtime, and environment variables.

$ gcloud app deploy

Deploy your app to upload and run it on App Engine. When you deploy your apps, you create versions of those apps and their corresponding services in App Engine

Flask quickstart

 

Rendering Templates

Generating HTML from within Python is not fun, and actually pretty cumbersome because you have to do the HTML escaping on your own to keep the

application secure. Because of that Flask configures the Jinja2 template engine for you automatically.

To render a template you can use the render_template() method. All you have to do is provide the name of the template

and the variables you want to pass to the template engine as

keyword arguments. Here’s a simple example of how to render a

template:

The Request Context

The request context keeps track of the request-level data during a request. Rather than passing the request object to each function that runs

during a request, the request and session proxies are accessed instead.

This is similar to the The Application Context

, which keeps track of the application-level data independent of a request. A corresponding application context is pushed when a request context

is pushed.

Flask Request

https://codelabs.developers.google.com/codelabs/cloud-app-engine-python3/#0

Write the web app

After Cloud Shell launches, you can use the command line to invoke the Cloud SDK gcloud command or other tools available on the virtual machine instance. You can use your $HOME directory in persistent disk storage to store files across projects and between Cloud Shell sessions. Your $HOME directory is private to you and cannot be accessed by other users.

Let's get started by creating a new folder in your $HOME directory for the application:

mkdir ~/helloworld

cd ~/helloworld

john@cloudshell:~(uconn-engr)$mkdir helloworld

john@cloudshell:~(uconn-engr)$ cd helloworld

john@cloudshell:~/helloworld (uconn-engr)$

Open editor - Highlight the helloworld directory 

 

Select new file

Enter main.py

Cut and paste python code into the new file

 

from flask import Flask

# If `entrypoint` is not defined in app.yaml, App Engine will look for an app

# called `app` in `main.py`.

app = Flask(__name__)

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

def hello():

    """Return a friendly HTTP greeting."""

    return 'Hello World!\n'

if __name__ == '__main__':

    # Used when running locally only. When deploying to Google App

    # Engine, a webserver process such as Gunicorn will serve the app. This

    # can be configured by adding an `entrypoint` to app.yaml.

    app.run(host='localhost', port=8080, debug=True)


Change message to “Hello UCONN World from your name”


 

Save the file

In the same directory create the requirements.txt file

To specify the dependencies of your web app, create a requirements.txt file in the root directory of your project with the exact version of Flask to use:

Flask==1.1.1

Save the file

In the same directory create the app.yaml file

To deploy your web app to App Engine, you need an app.yaml file. This configuration file defines your web app's settings for App Engine.

Create and edit the app.yaml file in the root directory of your project:

 

runtime: python37

Save the file

 

You must have the 3 following files:

app.yaml  main.py  requirements.txt

Go back to the terminal

Check if the files are in your directory

john@cloudshell:~/helloworld (uconn-engr)$ ls -l

total 4

-rw-r--r-- 1 john_iacovacci1 john_iacovacci1 17 Oct 24 20:29 app.yaml

-rw-r--r-- 1 john_iacovacci1 john_iacovacci1  0 Oct 24 20:14 main.py

-rw-r--r-- 1 john_iacovacci1 john_iacovacci1  0 Oct 24 20:22 requirements.txt

john@cloudshell:~/helloworld (uconn-engr)$

 

 

Deploy your web app with the following command:

gcloud app deploy

john@cloudshell:~/helloworld (uconn-engr)$ gcloud app deploy

 

 

 

john_iacovacci1@cloudshell:~/helloworld (uconn-engr)$ gcloud app deploy

Services to deploy:

descriptor:      [/home/john_iacovacci1/helloworld/app.yaml]

source:          [/home/john_iacovacci1/helloworld]

target project:  [uconn-engr]

target service:  [default]

target version:  [20201024t205323]

target url:      [https://uconn-engr.uc.r.appspot.com]

Do you want to continue (Y/n)?Y


Beginning deployment of service [default]...

Created .gcloudignore file. See `gcloud topic gcloudignore` for details.

╔════════════════════════════════════════════════════════════╗

╠═ Uploading 2 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

john_iacovacci1@cloudshell:~/helloworld (uconn-engr)$



 

 

Go to App Engine

 

 

Click on link

 

 


No comments:

Post a Comment

Office hours tomorrow(Tuesday) 5:00pm-6:00pm, 4/26/2021, 5:13 PM, English, 4/26/2021, 5:13 PM

Your assigned language is: English Classroom blog: googleclouduconn.blogspot.com 4/26/2021, 5:13 PM Office hours tomorrow(Tuesday) 5...