This repository was archived by the owner on May 29, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 88
Add FastAPI support with an ASGI Middleware #105
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
99 changes: 99 additions & 0 deletions
99
python/sqlcommenter-python/google/cloud/sqlcommenter/fastapi.py
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| #!/usr/bin/python | ||
| # | ||
| # Copyright 2022 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from __future__ import absolute_import | ||
|
|
||
| try: | ||
| from typing import Optional | ||
| from asgiref.compatibility import guarantee_single_callable | ||
| from contextvars import ContextVar | ||
| import fastapi | ||
| from fastapi import FastAPI | ||
| from starlette.routing import Match, Route | ||
| except ImportError: | ||
| fastapi = None | ||
|
|
||
| context = ContextVar("context", default={}) | ||
|
|
||
|
|
||
| def get_fastapi_info(): | ||
| """ | ||
| Get available info from the current FastAPI request, if we're in a | ||
| FastAPI request-response cycle. Else, return an empty dict. | ||
| """ | ||
| info = {} | ||
| if fastapi and context: | ||
| info = context.get() | ||
| return info | ||
|
|
||
|
|
||
| class SQLCommenterMiddleware: | ||
| """The ASGI application middleware. | ||
| This class is an ASGI middleware that augment SQL statements before execution, | ||
| with comments containing information about the code that caused its execution. | ||
|
|
||
| Args: | ||
| app: The ASGI application callable to forward requests to. | ||
| """ | ||
|
|
||
| def __init__(self, app): | ||
| self.app = guarantee_single_callable(app) | ||
|
|
||
| async def __call__(self, scope, receive, send): | ||
| """The ASGI application | ||
| Args: | ||
| scope: An ASGI environment. | ||
| receive: An awaitable callable yielding dictionaries | ||
| send: An awaitable callable taking a single dictionary as argument. | ||
| """ | ||
| if scope["type"] not in ("http", "websocket"): | ||
| return await self.app(scope, receive, send) | ||
|
|
||
| if not isinstance(scope["app"], FastAPI): | ||
| return await self.app(scope, receive, send) | ||
|
|
||
| fastapi_app = scope["app"] | ||
| info = _get_fastapi_info(fastapi_app, scope) | ||
| token = context.set(info) | ||
|
|
||
| try: | ||
| await self.app(scope, receive, send) | ||
| finally: | ||
| context.reset(token) | ||
|
|
||
|
|
||
| def _get_fastapi_info(fastapi_app: FastAPI, scope) -> dict: | ||
| info = { | ||
| "framework": 'fastapi:%s' % fastapi.__version__, | ||
| "app_name": fastapi_app.title, | ||
| } | ||
|
|
||
| route = _get_fastapi_route(fastapi_app, scope) | ||
| if route: | ||
| info["controller"] = route.name | ||
| info["route"] = route.path | ||
|
|
||
| return info | ||
|
|
||
|
|
||
| def _get_fastapi_route(fastapi_app: FastAPI, scope) -> Optional[Route]: | ||
| for route in fastapi_app.router.routes: | ||
| # Determine if any route matches the incoming scope, | ||
| # and return the route name if found. | ||
| match, child_scope = route.matches(scope) | ||
| if match == Match.FULL: | ||
| return child_scope["route"] | ||
| return None | ||
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
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
Empty file.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| from typing import Optional | ||
|
|
||
| from fastapi import FastAPI, status | ||
| from fastapi.responses import JSONResponse | ||
| from starlette.exceptions import HTTPException as StarletteHTTPException | ||
|
|
||
| from google.cloud.sqlcommenter.fastapi import SQLCommenterMiddleware, get_fastapi_info | ||
|
|
||
| app = FastAPI(title="SQLCommenter") | ||
|
|
||
| app.add_middleware(SQLCommenterMiddleware) | ||
|
|
||
|
|
||
| @app.get("/fastapi-info") | ||
| def fastapi_info(): | ||
| return get_fastapi_info() | ||
|
|
||
|
|
||
| @app.get("/items/{item_id}") | ||
| def read_item(item_id: int, q: Optional[str] = None): | ||
| return get_fastapi_info() | ||
|
|
||
|
|
||
| @app.exception_handler(StarletteHTTPException) | ||
| async def custom_http_exception_handler(request, exc): | ||
| return JSONResponse( | ||
| status_code=status.HTTP_404_NOT_FOUND, | ||
| content=get_fastapi_info(), | ||
| ) |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| #!/usr/bin/python | ||
| # | ||
| # Copyright 2019 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import json | ||
|
|
||
| import fastapi | ||
| import pytest | ||
| from starlette.testclient import TestClient | ||
|
|
||
| from google.cloud.sqlcommenter.fastapi import get_fastapi_info | ||
|
|
||
| from .app import app | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def client(): | ||
| client = TestClient(app) | ||
| yield client | ||
|
|
||
|
|
||
| def test_get_fastapi_info_in_request_context(client): | ||
| expected = { | ||
| 'app_name': 'SQLCommenter', | ||
| 'controller': 'fastapi_info', | ||
| 'framework': 'fastapi:%s' % fastapi.__version__, | ||
| 'route': '/fastapi-info', | ||
| } | ||
| resp = client.get('/fastapi-info') | ||
| assert json.loads(resp.content.decode('utf-8')) == expected | ||
|
|
||
|
|
||
| def test_get_fastapi_info_in_404_error_context(client): | ||
| expected = { | ||
| 'app_name': 'SQLCommenter', | ||
| 'framework': 'fastapi:%s' % fastapi.__version__, | ||
| } | ||
| resp = client.get('/doesnt-exist') | ||
| assert json.loads(resp.content.decode('utf-8')) == expected | ||
|
|
||
|
|
||
| def test_get_fastapi_info_outside_request_context(client): | ||
| assert get_fastapi_info() == {} |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -126,3 +126,38 @@ def test_route_disabled(self, get_info): | |
| "SELECT 1; /*controller='c',framework='flask'*/", | ||
| with_route=False, | ||
| ) | ||
|
|
||
|
|
||
| class FastAPITests(SQLAlchemyTestCase): | ||
| fastapi_info = { | ||
| 'framework': 'fastapi', | ||
| 'controller': 'c', | ||
| 'route': '/', | ||
| } | ||
|
|
||
| @mock.patch('google.cloud.sqlcommenter.sqlalchemy.executor.get_fastapi_info', return_value=fastapi_info) | ||
| def test_all_data(self, get_info): | ||
| self.assertSQL( | ||
| "SELECT 1; /*controller='c',framework='fastapi',route='/'*/", | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sorry to miss this one. This query: In general a
I have added one small PR for psycopg2 as of now (Waiting for review) and will create another for SQLAlchemy if the approach doesn't have major concern. |
||
| ) | ||
|
|
||
| @mock.patch('google.cloud.sqlcommenter.sqlalchemy.executor.get_fastapi_info', return_value=fastapi_info) | ||
| def test_framework_disabled(self, get_info): | ||
| self.assertSQL( | ||
| "SELECT 1; /*controller='c',route='/'*/", | ||
| with_framework=False, | ||
| ) | ||
|
|
||
| @mock.patch('google.cloud.sqlcommenter.sqlalchemy.executor.get_fastapi_info', return_value=fastapi_info) | ||
| def test_controller_disabled(self, get_info): | ||
| self.assertSQL( | ||
| "SELECT 1; /*framework='fastapi',route='/'*/", | ||
| with_controller=False, | ||
| ) | ||
|
|
||
| @mock.patch('google.cloud.sqlcommenter.sqlalchemy.executor.get_fastapi_info', return_value=fastapi_info) | ||
| def test_route_disabled(self, get_info): | ||
| self.assertSQL( | ||
| "SELECT 1; /*controller='c',framework='fastapi'*/", | ||
| with_route=False, | ||
| ) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.