Python で Cloud Functions の HTTP 関数を作成してデプロイする

Python で Cloud Functions の HTTP 関数を作成してデプロイする

このガイドでは、Python ランタイムを使用して Cloud Functions を記述するプロセスを説明します。Cloud Functions には次の 2 つのタイプがあります。

  • HTTP 関数。標準的な HTTP リクエストから呼び出します。
  • イベント ドリブン関数。Pub/Sub トピックのメッセージや Cloud Storage バケットの変更など、Cloud インフラストラクチャのイベントを処理するために使用します。

詳しくは、HTTP 関数の作成イベント ドリブン関数の作成をご覧ください。

始める前に

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Cloud Logging API を有効にします。

    API を有効にする

  5. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  6. Google Cloud プロジェクトで課金が有効になっていることを確認します

  7. Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Cloud Logging API を有効にします。

    API を有効にする

  8. gcloud CLI をインストールして初期化します
  9. 次のコマンドを使用して、gcloud コンポーネントを更新してインストールします。
    gcloud components update
  10. 開発環境を準備します。

    Python 設定ガイドに移動

関数を作成する

  1. 関数コードで使用するため、ローカル システムにディレクトリを作成します。

    Linux / Mac OS X

    mkdir ~/helloworld
    cd ~/helloworld
    

    Windows

    mkdir %HOMEPATH%\helloworld
    cd %HOMEPATH%\helloworld
    
  2. helloworld ディレクトリに、次の内容の main.py ファイルを作成します。

    
    import functions_framework
    
    from markupsafe import escape
    @functions_framework.http
    def hello_http(request):
        """HTTP Cloud Function.
        Args:
            request (flask.Request): The request object.
            <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
        Returns:
            The response text, or any set of values that can be turned into a
            Response object using `make_response`
            <https://flask.palletsprojects.com/en/1.1.x/api/#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 f"Hello {escape(name)}!"
    
    

    このサンプル関数は、HTTP リクエストで指定された名前を使用して挨拶を返します。名前が指定されていない場合は、「Hello World!」と返します。

依存関係を指定する

Python における依存関係は pip で管理され、requirements.txt というメタデータ ファイルで表現されます。このファイルは、関数のコードを含む main.py ファイルと同じディレクトリに置く必要があります。

  1. helloworld ディレクトリに、次の内容の requirements.txt ファイルを作成します。

      # An example requirements file. If your function has other dependencies,
      # add them below
      functions-framework==3.*
    

ローカルで関数をビルドしてテストする

関数をデプロイする前にローカルでビルドしてテストするには:

  1. Python 用のパッケージ インストーラpip)を実行して、パッケージの依存関係をインストールします。

    pip install -r requirements.txt
    PATH=$PATH:~/.local/bin
    
  2. Functions Framework を使用して関数をローカルで実行します。

    functions-framework-python --target hello_http
    
  3. ブラウザで http://localhost:8080 にアクセスするか、別のウィンドウから curl localhost:8080 を実行して、関数をテストします。

    詳細については、ローカル関数にリクエストを送信するをご覧ください。

関数をデプロイする

関数をデプロイするには、helloworld ディレクトリで次のコマンドを実行します。

  gcloud functions deploy python-http-function \
    --gen2 \
    --runtime=python312 \
    --region=REGION \
    --source=. \
    --entry-point=hello_http \
    --trigger-http \
    --allow-unauthenticated

REGION は、関数をデプロイする Google Cloud リージョンの名前に置き換えます(us-west1 など)。

オプションの --allow-unauthenticated フラグを使用すると、認証なしで関数にアクセスできます。

デプロイした関数をテストする

  1. 関数がデプロイされたら、gcloud functions deploy コマンドの出力で uri プロパティをメモするか、次のコマンドを使用して取得します。

    gcloud functions describe python-http-function \
      --region=REGION
    

    REGION は、関数をデプロイした Google Cloud リージョンの名前に置き換えます(us-west1 など)。

  2. ブラウザで、この URL にアクセスします。関数から「Hello World!」というメッセージが返されます。

関数のログを表示する

コマンドライン ツールを使用してログを表示する

関数のログは、Cloud Logging UI または Google Cloud CLI で確認できます。

gcloud CLI を使用して関数のログを表示するには、logs read コマンドを使用します。

  gcloud functions logs read \
    --gen2 \
    --limit=10 \
    --region=REGION \
    python-http-function

REGION は、関数をデプロイした Google Cloud リージョンの名前に置き換えます(us-west1 など)。

出力は次のようになります。

LEVEL: I
NAME: hello-http
TIME_UTC: 2023-06-01 19:33:42.991
LOG: Default STARTUP TCP probe succeeded after 1 attempt for container "hello__http-1" on port 8080.

LEVEL: I
NAME: hello-http
TIME_UTC: 2023-06-01 19:33:41.933
LOG:

LEVEL: I
NAME: hello-http
TIME_UTC: 2023-06-01 19:33:26.475
LOG: Default STARTUP TCP probe succeeded after 1 attempt for container "hello__http-1" on port 8080.

ロギング ダッシュボードでログを表示する

ロギング ダッシュボードで関数のログを表示するには、Cloud Functions の概要ページを開き、リストから関数の名前をクリックして、[ログ] タブをクリックします。