• Stars
    star
    670
  • Rank 64,762 (Top 2 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 4 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

Functions Framework for Python

PyPI version

Python unit CI Python lint CI Python conformace CI

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

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

The framework allows you to go from:

def hello(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 the CloudEvents spec
  • Portable between serverless platforms

Installation

Install the Functions Framework via pip:

pip install functions-framework

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

functions-framework==3.*

Quickstarts

Quickstart: HTTP Function (Hello World)

Create an main.py file with the following contents:

import functions_framework

@functions_framework.http
def hello(request):
    return "Hello world!"

Your function is passed a single parameter, (request), which is a Flask Request 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 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)

(You can also use functions-framework-python if you have multiple language frameworks installed).

Open http://localhost:8080/ in your browser and see Hello world!.

Or send requests to this function using curl from another terminal window:

curl localhost:8080
# Output: Hello world!

Quickstart: CloudEvent Function

Create an main.py file with the following contents:

import functions_framework

@functions_framework.cloud_event
def hello_cloud_event(cloud_event):
   print(f"Received event with ID: {cloud_event['id']} and data {cloud_event.data}")

Your function is passed a single CloudEvent parameter.

Run the following command to run hello_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 running functions-framework:

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

More info on sending CloudEvents payloads, see examples/cloud_run_cloud_events instruction.

Quickstart: Error handling

The framework includes an error handler that is similar to the flask.Flask.errorhandler function, which allows you to handle specific error types with a decorator:

import functions_framework


@functions_framework.errorhandler(ZeroDivisionError)
def handle_zero_division(e):
    return "I'm a teapot", 418


def function(request):
    1 / 0
    return "Success", 200

This function will catch the ZeroDivisionError and return a different response instead.

Quickstart: Pub/Sub emulator

  1. Create a main.py file with the following contents:

    def hello(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-project
    gcloud 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, using http://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-project
    export TOPIC_ID=my-topic
    export PUSH_SUBSCRIPTION_ID=my-subscription
    $(gcloud beta emulators pubsub env-init)
    
    git clone https://github.com/googleapis/python-pubsub.git
    cd python-pubsub/samples/snippets/
    pip install -r requirements.txt
    
    python publisher.py $PUBSUB_PROJECT_ID create $TOPIC_ID
    python subscriber.py $PUBSUB_PROJECT_ID create-push $TOPIC_ID $PUSH_SUBSCRIPTION_ID http://localhost:8080
    python 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-topic
    
    topic: "projects/my-project/topics/my-topic"
    push_config {
      push_endpoint: "http://localhost:8080"
    }
    ack_deadline_seconds: 10
    message_retention_duration {
      seconds: 604800
    }
    .
    Endpoint for subscription is: http://localhost:8080
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    Published 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-046
    Received 1
    127.0.0.1 - - [11/Aug/2021 14:42:22] "POST / HTTP/1.1" 200 -
    Received 2
    127.0.0.1 - - [11/Aug/2021 14:42:22] "POST / HTTP/1.1" 200 -
    Received 5
    127.0.0.1 - - [11/Aug/2021 14:42:22] "POST / HTTP/1.1" 200 -
    Received 6
    127.0.0.1 - - [11/Aug/2021 14:42:22] "POST / HTTP/1.1" 200 -
    Received 7
    127.0.0.1 - - [11/Aug/2021 14:42:22] "POST / HTTP/1.1" 200 -
    Received 8
    127.0.0.1 - - [11/Aug/2021 14:42:22] "POST / HTTP/1.1" 200 -
    Received 9
    127.0.0.1 - - [11/Aug/2021 14:42:39] "POST / HTTP/1.1" 200 -
    Received 3
    127.0.0.1 - - [11/Aug/2021 14:42:39] "POST / HTTP/1.1" 200 -
    Received 4
    127.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, see https://cloud.google.com/functions/docs/tutorials/pubsub#functions_helloworld_pubsub_tutorial-python

Quickstart: Build a Deployable Container

  1. Install Docker and the pack tool.

  2. Build a container from your function using the Functions buildpacks:

     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 using curl from another terminal window:

     curl localhost:8080
     # Output: Hello World!
    

Run your function on serverless platforms

Google Cloud Functions

This Functions Framework is based on the Python Runtime on Google Cloud Functions.

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

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

Cloud Run/Cloud Run on GKE

Once you've written your function and added the Functions Framework to your requirements.txt file, all that's left is to create a container image. Check out the Cloud Run quickstart for Python to create a container image and deploy it to Cloud Run. You'll write a Dockerfile when you build your container. This Dockerfile allows you to specify exactly what goes into your container (including custom binaries, a specific operating system, and more). Here is an example Dockerfile that calls Functions Framework.

If you want even more control over the environment, you can deploy your container image to Cloud Run on GKE. With Cloud Run on GKE, you can run your function on a GKE cluster, which gives you additional control over the environment (including use of GPU-based instances, longer timeouts and more).

Container environments based on Knative

Cloud Run and Cloud Run on GKE both implement the Knative 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 flag Environment variable Description
--host HOST The host on which the Functions Framework listens for requests. Default: 0.0.0.0
--port PORT The port on which the Functions Framework listens for requests. Default: 8080
--target FUNCTION_TARGET The name of the exported function to be invoked in response to requests. Default: function
--signature-type FUNCTION_SIGNATURE_TYPE The 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 or cloudevent
--source FUNCTION_SOURCE The path to the file containing your function. Default: main.py (in the current working directory)
--debug DEBUG A flag that allows to run functions-framework to run in debug mode, including live reloading. Default: False

Enable Google Cloud Function Events

The Functions Framework can unmarshall incoming Google Cloud Functions event payloads to event and context objects. These will be passed as arguments to your function when it receives a request. Note that your function must use the event-style function signature:

def hello(event, context):
    print(event)
    print(context)

To enable automatic unmarshalling, set the function signature type to event using the --signature-type command-line flag or the FUNCTION_SIGNATURE_TYPE environment variable. By default, the HTTP signature will be used and automatic event unmarshalling will be disabled.

For more details on this signature type, see the Google Cloud Functions documentation on background functions.

See the running example.

Advanced Examples

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

Contributing

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

More Repositories

1

microservices-demo

Sample cloud-first application with 10 microservices showcasing Kubernetes, Istio, and gRPC.
Go
15,783
star
2

terraformer

CLI tool to generate terraform files from existing infrastructure (reverse Terraform). Infrastructure to Code
Go
11,610
star
3

training-data-analyst

Labs and demos for courses for GCP Training (http://cloud.google.com/training).
Jupyter Notebook
7,479
star
4

python-docs-samples

Code samples used on cloud.google.com
Jupyter Notebook
6,985
star
5

generative-ai

Sample code and notebooks for Generative AI on Google Cloud
Jupyter Notebook
5,282
star
6

golang-samples

Sample apps and code written for Google Cloud in the Go programming language.
Go
4,136
star
7

nodejs-docs-samples

Node.js samples for Google Cloud Platform products.
JavaScript
2,762
star
8

tensorflow-without-a-phd

A crash course in six episodes for software developers who want to become machine learning practitioners.
Jupyter Notebook
2,735
star
9

professional-services

Common solutions and tools developed by Google Cloud's Professional Services team. This repository and its contents are not an officially supported Google product.
Python
2,730
star
10

gcsfuse

A user-space file system for interacting with Google Cloud Storage
Go
1,977
star
11

community

Java
1,908
star
12

PerfKitBenchmarker

PerfKit Benchmarker (PKB) contains a set of benchmarks to measure and compare cloud offerings. The benchmarks use default settings to reflect what most users will see. PerfKit Benchmarker is licensed under the Apache 2 license terms. Please make sure to read, understand and agree to the terms of the LICENSE and CONTRIBUTING files before proceeding.
Python
1,855
star
13

java-docs-samples

Java and Kotlin Code samples used on cloud.google.com
Java
1,610
star
14

ml-design-patterns

Source code accompanying O'Reilly book: Machine Learning Design Patterns
Jupyter Notebook
1,600
star
15

continuous-deployment-on-kubernetes

Get up and running with Jenkins on Google Kubernetes Engine
Shell
1,582
star
16

cloudml-samples

Cloud ML Engine repo. Please visit the new Vertex AI samples repo at https://github.com/GoogleCloudPlatform/vertex-ai-samples
Python
1,507
star
17

asl-ml-immersion

This repos contains notebooks for the Advanced Solutions Lab: ML Immersion
Jupyter Notebook
1,469
star
18

localllm

Python
1,449
star
19

cloud-builders

Builder images and examples commonly used for Google Cloud Build
Go
1,354
star
20

cloud-foundation-fabric

End-to-end modular samples and landing zones toolkit for Terraform on GCP.
HCL
1,343
star
21

vertex-ai-samples

Sample code and notebooks for Vertex AI, the end-to-end machine learning platform on Google Cloud
Jupyter Notebook
1,331
star
22

cloud-builders-community

Community-contributed images for Google Cloud Build
Go
1,233
star
23

data-science-on-gcp

Source code accompanying book: Data Science on the Google Cloud Platform, Valliappa Lakshmanan, O'Reilly 2017
Jupyter Notebook
1,230
star
24

berglas

A tool for managing secrets on Google Cloud
Go
1,223
star
25

cloud-sql-proxy

A utility for connecting securely to your Cloud SQL instances
Go
1,218
star
26

kubernetes-engine-samples

Sample applications for Google Kubernetes Engine (GKE)
HCL
1,178
star
27

functions-framework-nodejs

FaaS (Function as a service) framework for writing portable Node.js functions
TypeScript
1,162
star
28

cloud-vision

Sample code for Google Cloud Vision
Python
1,093
star
29

DataflowTemplates

Cloud Dataflow Google-provided templates for solving in-Cloud data tasks
Java
1,078
star
30

bigquery-utils

Useful scripts, udfs, views, and other utilities for migration and data warehouse operations in BigQuery.
Java
1,030
star
31

php-docs-samples

A collection of samples that demonstrate how to call Google Cloud services from PHP.
PHP
944
star
32

buildpacks

Builders and buildpacks designed to run on Google Cloud's container platforms
Go
937
star
33

deploymentmanager-samples

Deployment Manager samples and templates.
Jinja
928
star
34

bank-of-anthos

Retail banking sample application showcasing Kubernetes and Google Cloud
Java
926
star
35

cloud-foundation-toolkit

The Cloud Foundation toolkit provides GCP best practices as code.
Go
916
star
36

flask-talisman

HTTP security headers for Flask
Python
896
star
37

DataflowJavaSDK

Google Cloud Dataflow provides a simple, powerful model for building both batch and streaming parallel data processing pipelines.
857
star
38

gsutil

A command line tool for interacting with cloud storage services.
Python
857
star
39

k8s-config-connector

GCP Config Connector, a Kubernetes add-on for managing GCP resources
Go
826
star
40

nodejs-getting-started

A tutorial for creating a complete application using Node.js on Google Cloud Platform
JavaScript
800
star
41

keras-idiomatic-programmer

Books, Presentations, Workshops, Notebook Labs, and Model Zoo for Software Engineers and Data Scientists wanting to learn the TF.Keras Machine Learning framework
Jupyter Notebook
797
star
42

gcr-cleaner

Delete untagged image refs in Google Container Registry or Artifact Registry
Go
795
star
43

metacontroller

Lightweight Kubernetes controllers as a service
Go
790
star
44

getting-started-python

Code samples for using Python on Google Cloud Platform
Python
756
star
45

magic-modules

Add Google Cloud Platform support to Terraform
HTML
753
star
46

awesome-google-cloud

A curated list of awesome stuff for Google Cloud.
742
star
47

mlops-on-gcp

Jupyter Notebook
728
star
48

dotnet-docs-samples

.NET code samples used on https://cloud.google.com
C#
719
star
49

click-to-deploy

Source for Google Click to Deploy solutions listed on Google Cloud Marketplace.
Ruby
709
star
50

cloud-sdk-docker

Google Cloud CLI Docker Image - Docker Image containing the gcloud CLI and its bundled components.
Dockerfile
697
star
51

iap-desktop

IAP Desktop is a Windows application that provides zero-trust Remote Desktop and SSH access to Linux and Windows VMs on Google Cloud.
C#
687
star
52

tf-estimator-tutorials

This repository includes tutorials on how to use the TensorFlow estimator APIs to perform various ML tasks, in a systematic and standardised way
Jupyter Notebook
671
star
53

flink-on-k8s-operator

[DEPRECATED] Kubernetes operator for managing the lifecycle of Apache Flink and Beam applications.
Go
659
star
54

terraform-google-examples

Collection of examples for using Terraform with Google Cloud Platform.
HCL
573
star
55

functions-framework-dart

FaaS (Function as a service) framework for writing portable Dart functions
Dart
531
star
56

cloud-run-button

Let anyone deploy your GitHub repos to Google Cloud Run with a single click
Go
520
star
57

govanityurls

Use a custom domain in your Go import path
Go
513
star
58

bigquery-oreilly-book

Source code accompanying: BigQuery: The Definitive Guide by Lakshmanan & Tigani to be published by O'Reilly Media
Jupyter Notebook
499
star
59

getting-started-java

Java
478
star
60

ml-on-gcp

Machine Learning on Google Cloud Platform
Python
476
star
61

ipython-soccer-predictions

Sample iPython notebook with soccer predictions
Jupyter Notebook
473
star
62

covid-19-open-data

Datasets of daily time-series data related to COVID-19 for over 20,000 distinct locations around the world.
Python
470
star
63

ai-platform-samples

Official Repo for Google Cloud AI Platform. Find samples for Vertex AI, Google Cloud's new unified ML platform at: https://github.com/GoogleCloudPlatform/vertex-ai-samples
Jupyter Notebook
453
star
64

practical-ml-vision-book

Jupyter Notebook
441
star
65

gradle-appengine-templates

Freemarker based templates that build with the gradle-appengine-plugin
439
star
66

distributed-load-testing-using-kubernetes

Distributed load testing using Kubernetes on Google Container Engine
Smarty
438
star
67

terraform-validator

Terraform Validator is not an officially supported Google product; it is a library for conversion of Terraform plan data to CAI Assets. If you have been using terraform-validator directly in the past, we recommend migrating to `gcloud beta terraform vet`.
Go
436
star
68

hackathon-toolkit

GCP Hackathon Toolkit
HTML
434
star
69

monitoring-dashboard-samples

TypeScript
428
star
70

nodejs-docker

The Node.js Docker image used by Google App Engine Flexible.
TypeScript
406
star
71

cloud-ops-sandbox

Cloud Operations Sandbox is an open source collection of tools that helps practitioners to learn O11y and R9y practices from Google and apply them using Cloud Operations suite of tools.
HCL
398
star
72

cloud-code-vscode

Cloud Code for Visual Studio Code: Issues, Documentation and more
392
star
73

k8s-stackdriver

Go
390
star
74

professional-services-data-validator

Utility to compare data between homogeneous or heterogeneous environments to ensure source and target tables match
Python
375
star
75

cloud-code-samples

Code templates to make working with Kubernetes feel like editing and debugging local code.
Java
374
star
76

require-so-slow

`require`s taking too much time? Profile 'em.
TypeScript
373
star
77

functions-framework-go

FaaS (Function as a service) framework for writing portable Go functions
Go
373
star
78

k8s-multicluster-ingress

kubemci: Command line tool to configure L7 load balancers using multiple kubernetes clusters
Go
372
star
79

compute-image-packages

Packages for Google Compute Engine Linux images.
Python
370
star
80

healthcare

Python
367
star
81

android-docs-samples

Java
365
star
82

stackdriver-errors-js

Client-side JavaScript exception reporting library for Cloud Error Reporting
JavaScript
358
star
83

google-cloud-iot-arduino

Google Cloud IOT Example on ESP8266
C++
340
star
84

istio-samples

Istio demos and sample applications for GCP
Shell
331
star
85

ios-docs-samples

iOS samples that demonstrate APIs and services of Google Cloud Platform.
Swift
325
star
86

mlops-with-vertex-ai

An end-to-end example of MLOps on Google Cloud using TensorFlow, TFX, and Vertex AI
Jupyter Notebook
317
star
87

cloud-code-intellij

Plugin to support the Google Cloud Platform in IntelliJ IDEA - Docs and Issues Repository
315
star
88

gcping

The source for the CLI and web app at gcping.com
Go
303
star
89

spring-cloud-gcp

New home for Spring Cloud GCP development starting with version 2.0.
Java
299
star
90

airflow-operator

Kubernetes custom controller and CRDs to managing Airflow
Go
296
star
91

security-analytics

Community Security Analytics provides a set of community-driven audit & threat queries for Google Cloud
Python
289
star
92

elixir-samples

A collection of samples on using Elixir with Google Cloud Platform.
Elixir
289
star
93

gke-networking-recipes

Shell
286
star
94

datalab-samples

Jupyter Notebook
281
star
95

compute-archlinux-image-builder

A tool to build a Arch Linux Image for GCE
Shell
280
star
96

solutions-terraform-cloudbuild-gitops

HCL
276
star
97

kotlin-samples

Kotlin
276
star
98

gcpdiag

gcpdiag is a command-line diagnostics tool for GCP customers.
Python
268
star
99

PerfKitExplorer

PerfKit Explorer is a dashboarding and performance analysis tool built with Google technologies and easily extensible. PerfKit Explorer is licensed under the Apache 2 license terms. Please make sure to read, understand and agree to the terms of the LICENSE and CONTRIBUTING files before proceeding.
JavaScript
268
star
100

kube-jenkins-imager

Shell
261
star