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.

Guide structure

  1. Creating a GCP project using Cloud SDK
  2. Creating a function
  3. Specifying dependencies
  4. Deploying your function
  5. Testing your function

Creating a GCP project using Cloud SDK

  1. 登入您的 Google 帳戶。

    如果您沒有帳戶,請申請新帳戶

  2. 選取或建立 Google Cloud Platform 專案。

    前往「Manage resources」(管理資源) 頁面

  3. 請確認您已啟用 Google Cloud Platform 專案的計費功能。

    瞭解如何啟用計費功能

  4. 啟用Cloud Functions API。

    啟用 API

  5. Install and initialize the Cloud SDK.
  6. Update and install gcloud components:
    gcloud components update
  7. Need a command prompt? You can use the Google Cloud Shell. The Google Cloud Shell is a command line environment that already includes the Google Cloud SDK, so you don't need to install it. The Google Cloud SDK also comes preinstalled on Google Compute Engine Virtual Machines.

  8. Prepare your development environment.

    Go to the Python setup guide

Creating a function

  1. Create a directory on your local system for the function code:

    Linux or Mac OS X

    mkdir ~/gcf_hello_world
    cd ~/gcf_hello_world
    

    Windows

    mkdir %HOMEPATH%\gcf_hello_world
    cd %HOMEPATH%\gcf_hello_world
    
  2. Create a main.py file in the gcf_hello_world directory with the following contents:

    from flask import escape
    
    def hello_http(request):
        """HTTP Cloud Function.
        Args:
            request (flask.Request): The request object.
            <http://flask.pocoo.org/docs/1.0/api/#flask.Request>
        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(silent=True)
        request_args = request.args
    
        if request_json and 'name' in request_json:
            name = request_json['name']
        elif request_args and 'name' in request_args:
            name = request_args['name']
        else:
            name = 'World'
        return 'Hello {}!'.format(escape(name))

    This example function takes a name supplied in the HTTP request and returns a greeting, or "Hello World!" when no name is supplied.

Specifying dependencies

Dependencies in Python are managed with pip and expressed in a metadata file called requirements.txt. This file must be in the same directory as the main.py file that contains your function code.

  1. Create a requirements.txt file in the gcf_hello_world directory.

  2. Add the function's dependency, in this case the Flask package, to your requirements.txt file by adding the following line:

    Flask==1.0.2
    

Deploying the function

To deploy the function with an HTTP trigger, run the following command in the gcf_hello_world directory:

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

Testing the function

  1. When the function finishes deploying, take note of the httpsTrigger.url property or find it using the following command:

    gcloud functions describe hello_http
    

    It should look like this:

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http
  2. Visit this URL in your browser. You should see a "Hello World!" message.

    Try passing a name in the HTTP request, for example by using the following URL:

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http?name=NAME

    You should see the message "Hello NAME!"

Viewing logs

Using the command-line tool

Logs for Cloud Functions are viewable in the Stackdriver Logging UI, and via the gcloud command-line tool.

To view logs for your function with the gcloud tool, use the logs read command, followed by the name of the function:

gcloud functions logs read hello_http

The output should resemble the following:

LEVEL  NAME        EXECUTION_ID  TIME_UTC                 LOG
D      hello_http  pdb5ys2t022n  2019-09-18 23:29:09.791  Function execution started
D      hello_http  pdb5ys2t022n  2019-09-18 23:29:09.798  Function execution took 7 ms, finished with status code: 200

Using the Logging dashboard

You can also view logs for Cloud Functions from the Cloud Console.

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Functions Documentation