Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

FaaS (Function as a service) framework for writing portable Python functions

License

NotificationsYou must be signed in to change notification settings

GoogleCloudPlatform/functions-framework-python

Repository files navigation

PyPI version

Python unit CIPython lint CIPython conformace CISecurity Scorecard

An open source FaaS (Function as a service) framework for writing portablePython functions -- brought to you by the Google Cloud Functions team.

The Functions Framework lets you write lightweight functions that run in manydifferent environments, including:

The framework allows you to go from:

defhello(request):return"Hello world!"

To:

curl http://my-url# Output: Hello world!

All without needing to worry about writing an HTTP server or complicated request handling logic.

Features

  • Spin up a local development server for quick testing
  • Invoke a function in response to a request
  • Automatically unmarshal events conforming to theCloudEvents spec
  • Portable between serverless platforms

Installation

Install the Functions Framework viapip:

pip install functions-framework

Or, for deployment, add the Functions Framework to yourrequirements.txt file:

functions-framework==3.*

Quickstarts

Quickstart: HTTP Function (Hello World)

Create anmain.py file with the following contents:

importflaskimportfunctions_framework@functions_framework.httpdefhello(request:flask.Request)->flask.typing.ResponseReturnValue:return"Hello world!"

Your function is passed a single parameter,(request), which is a FlaskRequest object.

Run the following command:

functions-framework --target hello --debug* Serving Flask app"hello" (lazy loading)* Environment: production   WARNING: This is a development server. Do not use itin a production deployment.   Use a production WSGI server instead.* Debug mode: on* Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)

(You can also usefunctions-framework-python if you have multiplelanguage frameworks installed).

Openhttp://localhost:8080/ in your browser and seeHello world!.

Or send requests to this function usingcurl from another terminal window:

curl localhost:8080# Output: Hello world!

Quickstart: CloudEvent Function

Create anmain.py file with the following contents:

importfunctions_frameworkfromcloudevents.http.eventimportCloudEvent@functions_framework.cloud_eventdefhello_cloud_event(cloud_event:CloudEvent)->None:print(f"Received event with ID:{cloud_event['id']} and data{cloud_event.data}")

Your function is passed a singleCloudEvent parameter.

Run the following command to runhello_cloud_event target locally:

functions-framework --target=hello_cloud_event

In a different terminal,curl the Functions Framework server:

curl -X POST localhost:8080 \   -H"Content-Type: application/cloudevents+json" \   -d'{"specversion" : "1.0","type" : "example.com.cloud.event","source" : "https://example.com/cloudevents/pull","subject" : "123","id" : "A234-1234-1234","time" : "2018-04-05T17:31:00Z","data" : "hello world"}'

Output from the terminal runningfunctions-framework:

Received event with ID: A234-1234-1234 and data hello world

More info on sendingCloudEvents payloads, seeexamples/cloud_run_cloud_events instruction.

Quickstart: Error handling

The framework includes an error handler that is similar to theflask.Flask.errorhandlerfunction, which allows you to handle specific error types with a decorator:

importfunctions_framework@functions_framework.errorhandler(ZeroDivisionError)defhandle_zero_division(e):return"I'm a teapot",418deffunction(request):1/0return"Success",200

This function will catch theZeroDivisionError and return a differentresponse instead.

Quickstart: Pub/Sub emulator

  1. Create amain.py file with the following contents:

    defhello(event,context):print("Received",context.event_id)
  2. Start the Functions Framework on port 8080:

    functions-framework --target=hello --signature-type=event --debug --port=8080
  3. In a second terminal, start the Pub/Sub emulator on port 8085.

    export PUBSUB_PROJECT_ID=my-projectgcloud beta emulators pubsub start \    --project=$PUBSUB_PROJECT_ID \    --host-port=localhost:8085

    You should see the following after the Pub/Sub emulator has started successfully:

    [pubsub] INFO: Server started, listening on 8085
  4. In a third terminal, create a Pub/Sub topic and attach a push subscription to the topic, usinghttp://localhost:8080 as its push endpoint.Publish some messages to the topic. Observe your function getting triggered by the Pub/Sub messages.

    export PUBSUB_PROJECT_ID=my-projectexport TOPIC_ID=my-topicexport PUSH_SUBSCRIPTION_ID=my-subscription$(gcloud beta emulators pubsub env-init)git clone https://github.com/googleapis/python-pubsub.gitcd python-pubsub/samples/snippets/pip install -r requirements.txtpython publisher.py$PUBSUB_PROJECT_ID create$TOPIC_IDpython subscriber.py$PUBSUB_PROJECT_ID create-push$TOPIC_ID$PUSH_SUBSCRIPTION_ID http://localhost:8080python publisher.py$PUBSUB_PROJECT_ID publish$TOPIC_ID

    You should see the following after the commands have run successfully:

    Created topic: projects/my-project/topics/my-topictopic: "projects/my-project/topics/my-topic"push_config {  push_endpoint: "http://localhost:8080"}ack_deadline_seconds: 10message_retention_duration {  seconds: 604800}.Endpoint for subscription is: http://localhost:8080123456789Published messages to projects/my-project/topics/my-topic.

    And in the terminal where the Functions Framework is running:

     * Serving Flask app "hello" (lazy loading) * Environment: production   WARNING: This is a development server. Do not use it in a production deployment.   Use a production WSGI server instead. * Debug mode: on * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit) * Restarting with fsevents reloader * Debugger is active! * Debugger PIN: 911-794-046Received 1127.0.0.1 - - [11/Aug/2021 14:42:22] "POST / HTTP/1.1" 200 -Received 2127.0.0.1 - - [11/Aug/2021 14:42:22] "POST / HTTP/1.1" 200 -Received 5127.0.0.1 - - [11/Aug/2021 14:42:22] "POST / HTTP/1.1" 200 -Received 6127.0.0.1 - - [11/Aug/2021 14:42:22] "POST / HTTP/1.1" 200 -Received 7127.0.0.1 - - [11/Aug/2021 14:42:22] "POST / HTTP/1.1" 200 -Received 8127.0.0.1 - - [11/Aug/2021 14:42:22] "POST / HTTP/1.1" 200 -Received 9127.0.0.1 - - [11/Aug/2021 14:42:39] "POST / HTTP/1.1" 200 -Received 3127.0.0.1 - - [11/Aug/2021 14:42:39] "POST / HTTP/1.1" 200 -Received 4127.0.0.1 - - [11/Aug/2021 14:42:39] "POST / HTTP/1.1" 200 -

For more details on extracting data from a Pub/Sub event, seehttps://cloud.google.com/functions/docs/tutorials/pubsub#functions_helloworld_pubsub_tutorial-python

Quickstart: Build a Deployable Container

  1. InstallDocker and thepack tool.

  2. Build a container from your function using the Functionsbuildpacks:

     pack build \     --builder gcr.io/buildpacks/builder:v1 \     --env GOOGLE_FUNCTION_SIGNATURE_TYPE=http \     --env GOOGLE_FUNCTION_TARGET=hello \     my-first-function
  3. Start the built container:

     docker run --rm -p 8080:8080 my-first-function # Output: Serving function...
  4. Send requests to this function usingcurl from another terminal window:

     curl localhost:8080 # Output: Hello World!

Run your function on serverless platforms

Google Cloud Run functions

This Functions Framework is based on thePython Runtime on Google Cloud Functions.

On Cloud Functions, using the Functions Framework is not necessary: you don't need to add it to yourrequirements.txt file.

After you've written your function, you can simply deploy it from your local machine using thegcloud command-line tool.Check out the Cloud Functions quickstart.

Container environments based on Knative

Cloud Run and Cloud Run on GKE both implement theKnative Serving API. The Functions Framework is designed to be compatible with Knative environments. Just build and deploy your container to a Knative environment.

Configure the Functions Framework

You can configure the Functions Framework using command-line flags or environment variables. If you specify both, the environment variable will be ignored.

Command-line flagEnvironment variableDescription
--hostHOSTThe host on which the Functions Framework listens for requests. Default:0.0.0.0
--portPORTThe port on which the Functions Framework listens for requests. Default:8080
--targetFUNCTION_TARGETThe name of the exported function to be invoked in response to requests. Default:function
--signature-typeFUNCTION_SIGNATURE_TYPEThe signature used when writing your function. Controls unmarshalling rules and determines which arguments are used to invoke your function. Default:http; accepted values:http,event orcloudevent
--sourceFUNCTION_SOURCEThe path to the file containing your function. Default:main.py (in the current working directory)
--debugDEBUGA flag that allows to run functions-framework to run in debug mode, including live reloading. Default:False

Enable Google Cloud Run function Events

The Functions Framework can unmarshall incomingGoogle Cloud Run functionsevent payloads toevent andcontext objects.These will be passed as arguments to your function when it receives a request.Note that your function must use theevent-style function signature:

defhello(event,context):print(event)print(context)

To enable automatic unmarshalling, set the function signature type toeventusing the--signature-type command-line flag or theFUNCTION_SIGNATURE_TYPE environment variable. By default, the HTTPsignature will be used and automatic event unmarshalling will be disabled.

For more details on this signature type, see the Google Cloud Functionsdocumentation onbackground functions.

See therunning example.

Advanced Examples

More advanced guides can be found in theexamples/ directory.You can also find examples on using the CloudEvent Python SDKhere.

Contributing

Contributions to this library are welcome and encouraged. SeeCONTRIBUTING for more information on how to get started.

About

FaaS (Function as a service) framework for writing portable Python functions

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp