UCONN

UCONN
UCONN

App Engine Example

App Engine Hello World

1. Overview 

Google App Engine applications are easy to create, easy to maintain, and easy to scale as

your traffic and data storage needs change. With App Engine, there are no servers

to maintain. You simply upload your application and it's ready to go.

In this codelab, you will learn how to deploy a simple Python web app written

with the Flask web framework. Although this sample uses Flask, you can use other web frameworks, including Django,

Pyramid, Bottle, and web.py.

This tutorial is adapted f

rom https://cloud.google.com/appengine/docs/standard/python3/quickstart

What you'll learn

  • How to create a simple Python server on Google App Engine.

  • How to update the code without taking the server down.

What you'll need

  • Familiarity using Python

  • Familiarity with standard Linux text editors such as vim, emacs, or nano


2. Setup and requirements


Self-paced environment setup

Sign-in to the Google Cloud Console and create a new project or reuse an existing one.

If you don't already have a Gmail or Google Workspace account, you must create one.


The Project name is the display name for this project's participants. It is a character

string not used by Google APIs. You can always update it.

The Project ID is unique across all Google Cloud projects and is immutable (cannot be changed after it has been set). The Cloud Console auto-generates a

unique string; usually you don't care what it is. In most codelabs, you'll need to

reference your Project ID (typically identified as PROJECT_ID). If you don't like

the generated ID, you might generate another random one. Alternatively, you can

try your own, and see if it's available. It can't be changed after this step and remains

for the duration of the project.


For your information, there is a third value, a Project Number, which some APIs use.

Learn more about all three of these values in the documentation.

Caution: A project ID is globally unique and can't be used by anyone else after

you've selected it. You are the only user of that ID. Even if a project is deleted,

the ID can't be used again


Note: If you use a Gmail account, you can leave the default location set to

No organization. If you use a Google Workspace account, choose a location that

makes sense for your organization.


Next, you'll need to enable billing in the Cloud Console to use Cloud resources/APIs.

Running through this codelab won't cost much, if anything at all.

To shut down resources to avoid incurring billing beyond this tutorial,

you can delete the resources you created or delete the project.

New Google Cloud users are eligible for the $300 USD Free Trial program.


Start Cloud Shell


While Google Cloud can be operated remotely from your laptop, in this codelab

you will be using Cloud Shell, a command line environment running in the Cloud.


Activate Cloud Shell

From the Cloud Console, click Activate Cloud Shell 

If this is your first time starting Cloud Shell, you're presented with an intermediate

screen describing what it is. If you were presented with an intermediate screen,

click Continue.


It should only take a few moments to provision and connect to Cloud Shell.




This virtual machine is loaded with all the development tools needed. It offers a

persistent 5 GB home directory and runs in Google Cloud, greatly enhancing

network performance and authentication. Much, if not all, of your work in this codelab

can be done with a browser.


Once connected to Cloud Shell, you should see that you are authenticated and that the

project is set to your project ID.


Run the following command in Cloud Shell to confirm that you are authenticated:


gcloud auth list


Welcome to Cloud Shell! Type "help" to get started.

Your Cloud Platform project in this session is set to consummate-tine-433617-f0.

Use “gcloud config set project [PROJECT_ID]” to change to a different project.

bg1stamford@cloudshell:~ (consummate-tine-433617-f0)$ gcloud auth list


No credentialed accounts.


To login, run:

  $ gcloud auth login `ACCOUNT`


bg1stamford@cloudshell:~ (consummate-tine-433617-f0)$ 


Command output




 Credentialed Accounts

ACTIVE  ACCOUNT

*       <my_account>@<my_domain.com>


To set the active account, run:


$ gcloud config set account `ACCOUNT`

Note: The gcloud command-line tool is the powerful and unified command-line tool in

Google Cloud. It comes preinstalled in Cloud Shell. You will notice its support for tab

completion. You may be prompted to authenticate the first time you run a command.

For more information, see gcloud command-line tool overview.


Run the following command in Cloud Shell to confirm that the gcloud command

knows about your project:


gcloud config list project

Command output



bg1stamford@cloudshell:~ (consummate-tine-433617-f0)$ gcloud config list project

[core]

project = consummate-tine-433617-f0


Your active configuration is: [cloudshell-23674]

bg1stamford@cloudshell:~ (consummate-tine-433617-f0)$ 


[core]

project = <PROJECT_ID>

If it is not, you can set it with this command:



gcloud config set project <PROJECT_ID>

Command output



Updated property [core/project].

Note: If you're completing this tutorial outside of Cloud Shell, follow Set up

Application Default Credentials.


3. 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


bg1stamford@cloudshell:~ (consummate-tine-433617-f0)$ mkdir helloworld

cd ~/helloworld

bg1stamford@cloudshell:~ (consummate-tine-433617-f0)$ cd helloworld

Create a file named main.py:



Cloud Shell Editor button:


To directly edit the file with Cloud Shell Editor, use this command:



cloudshell edit main.py

main.py

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

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



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



This web app is a simple web service responding to HTTP GET requests

with the message Hello World!.


4. Define the dependencies

To specify the dependencies of your web app, go back to the terminal and

create a requirements.txt file in the root directory of your project,

with the exact version of Flask to use:



requirements.txt

To edit the file with Cloud Shell Editor, use this command:




cloudshell edit requirements.txt

requirements.txt

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

# https://pypi.org/project/Flask

Flask==3.0.2


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

The main dependency in your web app is Flask.



5. Configure the deployment


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.



From the terminal, create and edit the app.yaml file in the root directory of your project:



app.yaml

To edit the file with Cloud Shell Editor, use this command:



cloudshell edit app.yaml

App.yaml

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

runtime: python39


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


With this simple web app, you just need to specify your

Python version (e.g. 3.12 here). For more complicated web apps,

you can configure additional settings, like scaling, handlers for static files,

additional handlers, and other application elements like

environment variables and service names.

For more information and a list of all supported items, see the app.yaml reference.


6. Deploy the web app

A few steps are being skipped here. In a standard development cycle,

before deploying, you would first set up a local development environment,

install the same dependencies locally, and test the app locally.

See Setting up a Python development environment.


From the terminal, check the content of your directory:



ls

You should have the 3 following files:



app.yaml  main.py  requirements.txt

Deploy your web app with the following command:



gcloud app deploy


bg1stamford@cloudshell:~/helloworld (consummate-tine-433617-f0)$ gcloud app deploy


The first time, you need to choose a deployment region:


Please choose the region where you want your App Engine application located:


 [1] asia-east1    (supports standard and flexible)

 [2] asia-east2    (supports standard and flexible and search_api)

 [3] asia-northeast1 (supports standard and flexible and search_api)

 [4] asia-northeast2 (supports standard and flexible and search_api)

 [5] asia-northeast3 (supports standard and flexible and search_api)

 [6] asia-south1   (supports standard and flexible and search_api)

 [7] asia-southeast1 (supports standard and flexible)

 [8] asia-southeast2 (supports standard and flexible and search_api)

 [9] australia-southeast1 (supports standard and flexible and search_api)

 [10] europe-central2 (supports standard and flexible)

 [11] europe-west   (supports standard and flexible and search_api)

 [12] europe-west2  (supports standard and flexible and search_api)

 [13] europe-west3  (supports standard and flexible and search_api)

 [14] europe-west6  (supports standard and flexible and search_api)

 [15] northamerica-northeast1 (supports standard and flexible and search_api)

 [16] southamerica-east1 (supports standard and flexible and search_api)

 [17] us-central    (supports standard and flexible and search_api)

 [18] us-east1      (supports standard and flexible and search_api)

 [19] us-east4      (supports standard and flexible and search_api)

 [20] us-west1      (supports standard and flexible)

 [21] us-west2      (supports standard and flexible and search_api)

 [22] us-west3      (supports standard and flexible and search_api)

 [23] us-west4      (supports standard and flexible and search_api)

 [24] cancel


Please enter your numeric choice:  18




updating service [default]...failed.                                                                                                                            

ERROR: (gcloud.app.deploy) Error Response: [13] Failed to create cloud build: com.google.net.rpc3.client.RpcClientException: <eye3 title='/ArgoAdminNoCloudAudit.CreateBuild, FAILED_PRECONDITION'/> APPLICATION_ERROR;google.devtools.cloudbuild.v1/ArgoAdminNoCloudAudit.CreateBuild;invalid bucket "staging.consummate-tine-433617-f0.appspot.com"; service account consummate-tine-433617-f0@appspot.gserviceaccount.com does not have access to the bucket;AppErrorCode=9;StartTimeMs=1726179207525;unknown;ResFormat=uncompressed;ServerTimeSec=0.55492789;LogBytes=256;Non-FailFast;EndUserCredsRequested;EffSecLevel=privacy_and_integrity;ReqFormat=uncompressed;ReqID=8ca10c07710fc802;GlobalID=0;Server=[2002:ab0:ae8b:0:b0:3f0:7a39:3e6f]:4001.



Stack Overflow


bg1stamford@cloudshell:~/helloworld (consummate-tine-433617-f0)$ 




I ran into the same problem and what helped me was to ensure that the compute service API is activated (e.g. via gcloud services enable compute.googleapis.com) and to bind some missing IAM's roles/editor on XXXXXXXXX@cloudservices.gserviceaccount.com.

Side note: I consider the GCP project ID and number to be confidential and would recommend you not to share them publicly.



Need to enable Compute Engine API



Enable



bg1stamford@cloudshell:~/helloworld (consummate-tine-433617-f0)$ gcloud init


Welcome! This command will take you through the configuration of gcloud.


Settings from your current configuration [cloudshell-23674] are:

accessibility:

  screen_reader: 'True'

component_manager:

  disable_update_check: 'True'

compute:

  gce_metadata_read_timeout_sec: '30'

core:

  account: bg1stamford@gmail.com

  disable_usage_reporting: 'False'

  project: consummate-tine-433617-f0

metrics:

  environment: devshell


Pick configuration to use:

 [1] Re-initialize this configuration [cloudshell-23674] with new settings 

 [2] Create a new configuration

Please enter your numeric choice:  1



You are signed in as: [bg1stamford@gmail.com].


Pick cloud project to use: 

 [1] consummate-tine-433617-f0

 [2] Enter a project ID

 [3] Create a new project

Please enter numeric choice or text value (must exactly match list item):  1



Your current project has been set to: [consummate-tine-433617-f0].


Do you want to configure a default Compute Region and Zone? (Y/n)?  y


Which Google Compute Engine zone would you like to use as project default?

If you do not specify a zone via a command line flag while working with Compute Engine resources, the default is assumed.

 [1] us-east1-b

 [2] us-east1-c

 [3] us-east1-d

 [4] us-east4-c

 [5] us-east4-b

 [6] us-east4-a

 [7] us-central1-c

 [8] us-central1-a

 [9] us-central1-f

 [10] us-central1-b

 [11] us-west1-b

 [12] us-west1-c

 [13] us-west1-a

 [14] europe-west4-a

 [15] europe-west4-b

 [16] europe-west4-c

 [17] europe-west1-b

 [18] europe-west1-d

 [19] europe-west1-c

 [20] europe-west3-c

 [21] europe-west3-a

 [22] europe-west3-b

 [23] europe-west2-c

 [24] europe-west2-b

 [25] europe-west2-a

 [26] asia-east1-b

 [27] asia-east1-a

 [28] asia-east1-c

 [29] asia-southeast1-b

 [30] asia-southeast1-a

 [31] asia-southeast1-c

 [32] asia-northeast1-b

 [33] asia-northeast1-c

 [34] asia-northeast1-a

 [35] asia-south1-c

 [36] asia-south1-b

 [37] asia-south1-a

 [38] australia-southeast1-b

 [39] australia-southeast1-c

 [40] australia-southeast1-a

 [41] southamerica-east1-b

 [42] southamerica-east1-c

[43] southamerica-east1-a

 [44] africa-south1-a

 [45] africa-south1-b

 [46] africa-south1-c

 [47] asia-east2-a

 [48] asia-east2-b

 [49] asia-east2-c

 [50] asia-northeast2-a

Did not print [72] options.

Too many options [122]. Enter "list" at prompt to print choices fully.

Please enter numeric choice or text value (must exactly match list item): 


Your project default Compute Engine zone has been set to [us-east1-b].

You can change it by running [gcloud config set compute/zone NAME].


Your project default Compute Engine region has been set to [us-east1].

You can change it by running [gcloud config set compute/region NAME].


Created a default .boto configuration file at [/home/bg1stamford/.boto]. See this file and

[https://cloud.google.com/storage/docs/gsutil/commands/config] for more

information about configuring Google Cloud Storage.

The Google Cloud CLI is configured and ready to use!


* Commands that require authentication will use bg1stamford@gmail.com by default

* Commands will reference project `consummate-tine-433617-f0` by default

* Compute Engine commands will use region `us-east1` by default

* Compute Engine commands will use zone `us-east1-b` by default


Run `gcloud help config` to learn how to change individual settings


This gcloud configuration is called [cloudshell-23674]. You can create additional configurations if you work with multiple accounts and/or projects.

Run `gcloud topic configurations` to learn more.


Some things to try next:


* Run `gcloud --help` to see the Cloud Platform services you can interact with. And run `gcloud help COMMAND` to get help on any gcloud command.

* Run `gcloud topic --help` to learn about advanced features of the CLI like arg files and output formatting

* Run `gcloud cheat-sheet` to see a roster of go-to `gcloud` commands.


Your current configuration has been set to: [cloudshell-23674]


You can skip diagnostics next time by using the following flag:

  gcloud init --skip-diagnostics


Network diagnostic detects and fixes local network connection issues.

Checking network connection...done.                                                                                                                             

Reachability Check passed.

Network diagnostic passed (1/1 checks passed).


Choose the account you want to use for this configuration.

To use a federated user account, exit this command and sign in to the gcloud CLI with your login configuration file, then run this command again.


Select an account:

 [1] bg1stamford@gmail.com

 [2] Sign in with a new Google Account

 [3] Skip this step

Please enter your numeric choice:  1



Your project default Compute Engine zone has been set to [us-east1-b].

You can change it by running [gcloud config set compute/zone NAME].


Your project default Compute Engine region has been set to [us-east1].

You can change it by running [gcloud config set compute/region NAME].


Created a default .boto configuration file at [/home/bg1stamford/.boto]. See this file and

[https://cloud.google.com/storage/docs/gsutil/commands/config] for more

information about configuring Google Cloud Storage.

The Google Cloud CLI is configured and ready to use!


* Commands that require authentication will use bg1stamford@gmail.com by default

* Commands will reference project `consummate-tine-433617-f0` by default

* Compute Engine commands will use region `us-east1` by default

* Compute Engine commands will use zone `us-east1-b` by default


Run `gcloud help config` to learn how to change individual settings


This gcloud configuration is called [cloudshell-23674]. You can create additional configurations if you work with multiple accounts and/or projects.

Run `gcloud topic configurations` to learn more.


Some things to try next:


* Run `gcloud --help` to see the Cloud Platform services you can interact with. And run `gcloud help COMMAND` to get help on any gcloud command.

* Run `gcloud topic --help` to learn about advanced features of the CLI like arg files and output formatting

* Run `gcloud cheat-sheet` to see a roster of go-to `gcloud` commands.


bg1stamford@cloudshell:~/helloworld (consummate-tine-433617-f0)$ gcloud app deploy

Services to deploy:


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

source:                      [/home/bg1stamford/helloworld]

target project:              [consummate-tine-433617-f0]

target service:              [default]

target version:              [20240912t222447]

target url:                  [https://consummate-tine-433617-f0.ue.r.appspot.com]

target service account:      [consummate-tine-433617-f0@appspot.gserviceaccount.com]



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



Beginning deployment of service [default]...

Uploading 0 files to Google Cloud Storage

100%

File upload done.

Updating service [default]...done.                                                                                                                              

Setting traffic split for service [default]...done.                                                                                                             

Deployed service [default] to [https://consummate-tine-433617-f0.ue.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

bg1stamford@cloudshell:~/helloworld (consummate-tine-433617-f0)$ gcloud app browse

Did not detect your browser. Go to this link to view your app:


https://consummate-tine-433617-f0.ue.r.appspot.com



bg1stamford@cloudshell:~/helloworld (consummate-tine-433617-f0)$ 


7. Test the web app

Your web app is ready to respond to HTTP requests on https://PROJECT_ID.REGION_ID.r.appspot.com.


First, retrieve your web app hostname with the gcloud app describe command:



APPENGINE_HOSTNAME=$(gcloud app describe --format "value(defaultHostname)")

Test your web app with this simple HTTP GET request:



curl https://$APPENGINE_HOSTNAME

You should get the following answer:



Hello World!

Your web app can be served via a custom domain, such as example.com, instead of the default appspot.com address. See Mapping Custom Domains.


Summary

In the previous steps, you set up a simple Python web app, ran, and deployed the application on App Engine.



8. Update the web app


Modify your web app by changing the hello() function body in your main.py file.


To edit the file with Cloud Shell Editor, use this command:



cloudshell edit main.py

main.py


import flask


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

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

app = flask.Flask(__name__)



@app.get("/")

def hello():

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

    # return "Hello World!\n"  # ← Replace this line

    who = flask.request.args.get("who", "World")

    return f"Hello {who}!\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)

Flask's request context object is used here to handle an optional parameter in the HTTP GET request.


From the terminal, redeploy to update your web app:


gcloud app deploy --quiet

The --quiet flag disables the interactive prompt, which directly launches the deployment.


The new version of your app gets deployed:


Beginning deployment of service [default]...

Uploading 1 file to Google Cloud Storage 

...

Deployed service [default] to [https://PROJECT_ID.REGION_ID.r.appspot.com]

The new version is transparently deployed and traffic is automatically routed to it (if successfully deployed).


Test the new version of your web app, exactly as you did previously:


curl https://$APPENGINE_HOSTNAME

You should get the same answer:


Hello World!

Test it with the optional parameter:


curl https://$APPENGINE_HOSTNAME?who=Universe

You should get the following answer:


Hello Universe!


Summary

In this step, you updated and redeployed your web app without any service interruption.


Back

Next

9. Congratulations!

You learned to write your first App Engine web application in Python!


Learn more

App Engine Documentation: https://cloud.google.com/appengine

Explore this tutorial to write a fully-fledged Python app on App Engine: https://cloud.google.com/appengine/docs/standard/python3/building-app

License

This work is licensed under a Creative Commons Attribution 2.0 Generic License.



No comments:

Post a Comment

Disable Billing

Search for Billing Manage billing accounts Go to MYPROJECTS CLICK ON THE 3 BUTTON Actions Then hit disable