Skip to content

feat: support asgi frameworks directly in asgi mode #382

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ functions_framework = ["py.typed"]
dev = [
"black>=23.3.0",
"build>=1.1.1",
"fastapi>=0.100.0",
"isort>=5.11.5",
"pretend>=1.0.9",
"pytest>=7.4.4",
Expand Down
37 changes: 36 additions & 1 deletion src/functions_framework/aio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.routing import Route
from starlette.routing import Mount, Route
except ImportError:
raise FunctionsFrameworkException(
"Starlette is not installed. Install the framework with the 'async' extra: "
Expand Down Expand Up @@ -247,6 +247,22 @@ def create_asgi_app(target=None, source=None, signature_type=None):
_configure_app_execution_id_logging()

spec.loader.exec_module(source_module)

# Check if the target function is an ASGI app
if hasattr(source_module, target):
target_obj = getattr(source_module, target)
if _is_asgi_app(target_obj):
app = Starlette(
routes=[
Mount("/", app=target_obj),
],
middleware=[
Middleware(ExceptionHandlerMiddleware),
Middleware(execution_id.AsgiMiddleware),
],
)
return app

function = _function_registry.get_user_function(source, source_module, target)
signature_type = _function_registry.get_func_signature_type(target, signature_type)

Expand Down Expand Up @@ -326,4 +342,23 @@ async def __call__(self, scope, receive, send):
await self.app(scope, receive, send)


def _is_asgi_app(target) -> bool:
"""Check if an target looks like an ASGI application."""
if not callable(target):
return False

# Check for common ASGI framework attributes
# FastAPI, Starlette, Quart all have these
if hasattr(target, "routes") or hasattr(target, "router"):
return True

# Check if it's a coroutine function with 3 params (scope, receive, send)
if inspect.iscoroutinefunction(target):
sig = inspect.signature(target)
params = list(sig.parameters.keys())
return len(params) == 3

return False


app = LazyASGIApp()
88 changes: 84 additions & 4 deletions tests/test_aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,18 @@
import sys
import tempfile

from unittest.mock import Mock, call

if sys.version_info >= (3, 8):
from unittest.mock import AsyncMock
from unittest.mock import AsyncMock, Mock, call

import pytest

from starlette.testclient import TestClient

from functions_framework import exceptions
from functions_framework.aio import (
LazyASGIApp,
_cloudevent_func_wrapper,
_http_func_wrapper,
_is_asgi_app,
create_asgi_app,
)

Expand Down Expand Up @@ -192,3 +192,83 @@ def sync_cloud_event(event):
assert called_with_event is not None
assert called_with_event["type"] == "test.event"
assert called_with_event["source"] == "test-source"


def test_detects_starlette_app():
from starlette.applications import Starlette

app = Starlette()
assert _is_asgi_app(app) is True


def test_detects_fastapi_app():
from fastapi import FastAPI

app = FastAPI()
assert _is_asgi_app(app) is True


def test_detects_bare_asgi_callable():
async def asgi_app(scope, receive, send):
pass

assert _is_asgi_app(asgi_app) is True


def test_rejects_non_asgi_functions():
def regular_function(request):
return "response"

async def async_function(request):
return "response"

async def wrong_params(a, b):
pass

assert _is_asgi_app(regular_function) is False
assert _is_asgi_app(async_function) is False
assert _is_asgi_app(wrong_params) is False
assert _is_asgi_app("not a function") is False


def test_fastapi_app():
source = str(TEST_FUNCTIONS_DIR / "asgi_apps" / "fastapi_app.py")
app = create_asgi_app(target="app", source=source)
client = TestClient(app)

response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello World"}

response = client.get("/items/42")
assert response.status_code == 200
assert response.json() == {"item_id": 42}


def test_bare_asgi_app():
source = str(TEST_FUNCTIONS_DIR / "asgi_apps" / "bare_asgi.py")
app = create_asgi_app(target="app", source=source)
client = TestClient(app)

response = client.get("/")
assert response.status_code == 200
assert response.text == "Hello from ASGI"


def test_starlette_app():
source = str(TEST_FUNCTIONS_DIR / "asgi_apps" / "starlette_app.py")
app = create_asgi_app(target="app", source=source)
client = TestClient(app)

response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello from Starlette"}


def test_error_handling_in_asgi_app():
source = str(TEST_FUNCTIONS_DIR / "asgi_apps" / "fastapi_app.py")
app = create_asgi_app(target="app", source=source)
client = TestClient(app)

response = client.get("/nonexistent")
assert response.status_code == 404
16 changes: 16 additions & 0 deletions tests/test_functions/asgi_apps/bare_asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
async def app(scope, receive, send):
assert scope["type"] == "http"

await send(
{
"type": "http.response.start",
"status": 200,
"headers": [[b"content-type", b"text/plain"]],
}
)
await send(
{
"type": "http.response.body",
"body": b"Hello from ASGI",
}
)
13 changes: 13 additions & 0 deletions tests/test_functions/asgi_apps/fastapi_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
return {"message": "Hello World"}


@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
14 changes: 14 additions & 0 deletions tests/test_functions/asgi_apps/starlette_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route


async def homepage(request):
return JSONResponse({"message": "Hello from Starlette"})


app = Starlette(
routes=[
Route("/", homepage),
]
)
3 changes: 1 addition & 2 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ deps =
pytest-cov
pytest-integration
pretend
py,py38,py39,py310,py311,py312: fastapi
extras =
async
setenv =
Expand All @@ -48,8 +49,6 @@ deps =
isort
mypy
build
extras =
async
commands =
black --check src tests conftest.py --exclude tests/test_functions/background_load_error/main.py
isort -c src tests conftest.py
Expand Down
Loading