Skip to content

Instantly share code, notes, and snippets.

@danielomiya
Last active August 24, 2023 17:03
Show Gist options
  • Select an option

  • Save danielomiya/68985c7a3ae23ea067a5934729f13c50 to your computer and use it in GitHub Desktop.

Select an option

Save danielomiya/68985c7a3ae23ea067a5934729f13c50 to your computer and use it in GitHub Desktop.
Flask wrapper for Cloud Functions
from http import HTTPStatus
import flask.typing as ft
from flask import Flask
from wrapper import as_cloudfunction
app = Flask(__name__)
@app.get("/")
def get_all() -> ft.ResponseReturnValue:
return {"some": "message"}, HTTPStatus.OK
@app.get("/<int:id>")
def get_by_id(id: int) -> ft.ResponseReturnValue:
return {"my": "entity"}, HTTPStatus.OK
main = as_cloudfunction(app)
import typing as t
import functions_framework
if t.TYPE_CHECKING:
from flask import Flask, Request, Response
def as_cloudfunction(app: "Flask") -> t.Callable[["Request"], "Response"]:
"""
Receives a Flask App and converts it into a Cloud Function callable
:param app: the Flask app
:return: a Cloud Function function
"""
@functions_framework.http
def func(request: "Request") -> "Response":
# see more at: https://stackoverflow.com/a/55576232
# and GoogleCloudPlatform/functions-framework-python#98
ctx = app.test_request_context(
path=request.path,
method=request.method,
)
ctx.request = request
with ctx:
return app.full_dispatch_request()
return func
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment