Functions Framework for Python
Functions Framework for Python is an open-source FaaS (Function as a Service) framework designed for writing portable Python functions. It allows developers to test their Google Cloud Functions locally, run them in other serverless environments, or deploy them directly to Google Cloud. The current version is 3.10.1, and it maintains an active release cadence with frequent patch and minor updates, typically every 1-3 months.
Warnings
- breaking Functions Framework v3.8.3 and later require Flask 2.0 or higher. If your project uses an older version of Flask, you may encounter `ImportError` or other compatibility issues.
- gotcha When running locally, you must specify the target function using the `--target` flag (e.g., `functions-framework --target my_function`). Failing to do so will result in an error indicating no target was found.
- gotcha Ensure your function signature matches the expected type (HTTP or CloudEvent). HTTP functions take a `flask.Request` object. CloudEvent functions take a `cloudevents.CloudEvent` object.
- gotcha For CloudEvents, access the event data via `event.data` for the actual payload. CloudEvents often wrap the original payload (e.g., Pub/Sub messages are nested).
- breaking Version 3.10.1 corrected the `cloudevents` dependency to allow `1.11.0`. Older `functions-framework` versions might have had improperly constrained `cloudevents` dependencies, potentially leading to issues if `cloudevents` was upgraded to an incompatible version.
Install
-
pip install functions-framework
Imports
- Request
from flask import Request
- CloudEvent
from cloudevents.http import CloudEvent
Quickstart
# main.py
def hello_http(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): The request object.
Returns:
The response text, or any set of values that can be turned into a Response object
using `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 {name}!'
# To run locally:
# 1. Save this as main.py
# 2. Run from your terminal: functions-framework --target hello_http
# 3. Access at http://localhost:8080/