Last active
August 24, 2023 17:03
-
-
Save danielomiya/68985c7a3ae23ea067a5934729f13c50 to your computer and use it in GitHub Desktop.
Flask wrapper for Cloud Functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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