Cloud Functions - Python

 

Cloud Functions - Python

 

Google Cloud Functions is a lightweight compute solution for developers to create single-purpose, stand-alone functions that respond to Cloud events without the need to manage a server or runtime environment.

 

Your First Function: Python

This guide takes you through the process of writing a Cloud Function using the Python runtime. There are two types of Cloud Functions:

  • An HTTP function, which you invoke from standard HTTP requests.

  • A background function, which you use to handle events from your Cloud infrastructure, such as messages on a Cloud Pub/Sub topic, or changes in a Cloud Storage bucket.

The sample shows how to create a simple HTTP function.

HTTP stands for Hyper Text Transfer Protocol

WWW is about communication between web clients and servers

Communication between client computers and web servers is done by sending HTTP Requests and receiving HTTP Responses

HTTP Request / Response

Communication between clients and servers is done by requests and responses:

  1. A client (a browser) sends an HTTP request to the web

  2. An web server receives the request

  3. The server runs an application to process the request

  4. The server returns an HTTP response (output) to the browser

  5. The client (the browser) receives the response


The HTTP Request Circle

A typical HTTP request / response circle:

  1. The browser requests an HTML page. The server returns an HTML file.

  2. The browser requests a style sheet. The server returns a CSS file.

  3. The browser requests an JPG image. The server returns a JPG file.

  4. The browser requests JavaScript code. The server returns a JS file

  5. The browser requests data. The server returns data (in XML or JSON).

  6.  

 

 

Flask

Flask (source code) is a Python web framework built with a small core and easy-to-extend philosophy.

 

Flask is considered more Pythonic than the Django web framework because in common situations the equivalent Flask web application is more explicit. Flask is also easy to get started with as a beginner because there is little boilerplate code for getting a simple app up and running.

For example, here is a valid "Hello, world!" web application with Flask:

from flask import Flask

app = Flask(__name__)



@app.route('/')

def hello_world():

    return 'Hello, World!'


if __name__ == '__main__':

    app.run()

 

The above code shows "Hello, World!" on localhost port 5000 in a web browser when run with the python app.py command and the Flask library installed.

The equivalent "Hello, World!" web application using the Django web framework would involve significantly more boilerplate code.

Flask was also written several years after Django and therefore learned from the Python community's reactions as the framework evolved. Jökull Sólberg wrote a great piece articulating to this effect in his experience switching between Flask and Django.


Create a function

  1. Open the Functions Overview page in the Cloud Console:
    Go to the Cloud Functions Overview page
    Make sure that the project for which you enabled Cloud Functions is selected.

  2. Click Create function.

  3. Name your function.

  4. In the Trigger field, select HTTP.

  5. In the Authentication field, select Allow unauthenticated invocations.

  6. Click Save to save your changes, and then click Next.

  7. In the Source code field, select Inline editor. In this exercise, you will use the default function provided in the editor.

  8. Use the Runtime dropdown to select the desired Python runtime.



 

Python Quickstart






Create function



 

Name the function

 

 

Save the functions hello-world

Click next trigger set to HTTP

Choose python 3.7 for runtime 

 

 

Remove template code

 

 

Paste new code and deploy

 

Cloud Functions is a serverless execution environment for building and connecting cloud services. With Cloud Functions you write simple, single-purpose functions that are attached to events emitted from your cloud infrastructure and services. Your function is triggered when an event being watched is fired.

This page shows you how to create and deploy a Python Cloud Function using the Cloud Console. When this function is triggered by an HTTP request, it writes a message:

def hello_world(request):

    """Responds to any HTTP request.

    Args:

        request (flask.Request): HTTP request object.

    Returns:

        The response text or any set of values that can be turned into a

        Response object using

        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.

    """

    request_json = request.get_json()

    if request.args and 'message' in request.args:

        return request.args.get('message')

    elif request_json and 'message' in request_json:

        return request_json['message']

    else:

        return f'Hello UCONN World!'



Service account

uconn-engr@appspot.gserviceaccount.com



Deploy the function

  1. At the bottom of the page, click Deploy.

  2. After clicking Deploy, Cloud Console redirects to the Cloud Functions Overview page.
    While the function is being deployed, the icon next to it is a small spinner. After it finishes deploying, the spinner turns to a green check mark:
    Screenshot that shows function deployment process

Test the function

  1. Display the menu for your function, and click Test function.
    Screenshot that shows function testing process

  2. On the testing page, click Test the function.
    The Output screen displays the text "Hello World!"

  3. Now change the message. In the Triggering Event field, enter the text {"message":"Hello, YOUR_NAME!"}, replacing YOUR_NAME with a name, and click Test the function.
    For example, suppose you entered the name "Rowan". In the Output field, you would see the message Hello, Rowan!.
    In the Logs field, a status code of 200 indicates success.
    Screenshot showing Logs field with 200 code, indicating success




The Python Runtime

Cloud Functions supports the following Python runtimes:

  • Python 3.7

  • Python 3.8 (beta)

For instructions on how to prepare your local machine for Python development, see Setting Up a Python Development Environment.

To get started with Python on Cloud Functions, see the Quickstart.

Selecting the runtime

You can select the Python runtime for your function during deployment.

gcloud

Console

If you are using the gcloud command-line tool, you can specify the runtime by using the --runtime parameter. For example:

gcloud functions deploy NAME --runtime python37 --trigger-http

For more arguments that you can specify when you are deploying, see Deploy using the gcloud tool.

Execution environment

The execution environment includes the runtime, the operating system, packages, and a library that invokes your function.

The Python runtime uses an execution environment based on Ubuntu 18.04 with Python version 3.7.6. See Cloud Functions Execution Environment for more information.

Source code structure

In order for Cloud Functions to find your function's definition, each runtime has certain structuring requirements for your source code. See Writing Cloud Functions for more information.

Specifying dependencies

There are two ways to specify dependencies for Cloud Functions written in Python: using the pip package manager's requirements.txt file or packaging local dependencies alongside your function. For more information, see Specifying dependencies in Python.

Events and Triggers

This page describes the concept of events in the context of Google Cloud Functions. It also covers how to create and associate triggers with functions so that they will execute when an event is fired.

Events

Events are things that happen within your cloud environment that you might want to take action on. These might be changes to data in a database, files added to a storage system, or a new virtual machine instance being created. Currently, Cloud Functions supports events from the following providers:

For examples of how to associate triggers with functions so that they execute when an event is fired, see the tutorials.

Event data

When an event triggers the execution of your Cloud Function, data associated with the event is passed via the function's parameters. The type of event determines the parameters passed to your function. HTTP request events trigger HTTP functions, and the other event types trigger background functions.

Node.js

Python

Go

Java

In the Node.js runtime, functions take the following parameters:

  • HTTP Functions
    Your function is passed the ExpressJS parameters (request, response). Use the response parameter to send a response.

  • Background Functions
    Your function is passed the parameters (data, context, callback). See Background Functions for more details on these parameters.

Triggers

Creating a response to an event is done with a trigger. A trigger is a declaration that you are interested in a certain event or set of events. Binding a function to a trigger allows you to capture and act on events.

Note: Events are delivered at least once, which means that rarely, spurious duplicates can occur.

Below is a table of the types of triggers supported and the flags used to specify them during command-line deployment:



Trigger

Command-line flag

HTTP

--trigger-http

Google Cloud Pub/Sub

--trigger-topic TOPIC_NAME

Other sources (e.g. Firebase)

--trigger-event EVENT_TYPE --trigger-resource RESOURCE

For more information on the command-line flags, see the gcloud functions deploy reference.

Binding of triggers to functions happens at deployment time either via the gcloud command-line tool, the UI or Cloud Functions API. Functions and triggers are bound to each other on a many-to-one basis. In other words, you cannot bind the same function to more than a single trigger at a time. You can, however, have the same trigger cause multiple functions to execute by simply deploying two different functions with the same trigger.


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