Skip to content
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

fix (#1793): FastStream Response support in FastAPI integration #1796

Merged
merged 2 commits into from
Sep 16, 2024
Merged
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
17 changes: 10 additions & 7 deletions faststream/broker/fastapi/route.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from starlette.requests import Request

from faststream.broker.fastapi.get_dependant import get_fastapi_native_dependant
from faststream.broker.response import Response, ensure_response
from faststream.broker.types import P_HandlerParams, T_HandlerReturn

from ._compat import (
Expand Down Expand Up @@ -186,15 +187,15 @@ def make_fastapi_execution(
response_model_exclude_none: bool,
) -> Callable[
["StreamMessage", "NativeMessage[Any]"],
Awaitable[Any],
Awaitable[Response],
]:
"""Creates a FastAPI application."""
is_coroutine = asyncio.iscoroutinefunction(dependent.call)

async def app(
request: "StreamMessage",
raw_message: "NativeMessage[Any]", # to support BackgroundTasks by middleware
) -> Any:
) -> Response:
"""Consume StreamMessage and return user function result."""
async with AsyncExitStack() as stack:
if FASTAPI_V106:
Expand All @@ -215,14 +216,16 @@ async def app(
if solved_result.errors:
raise_fastapi_validation_error(solved_result.errors, request._body) # type: ignore[arg-type]

raw_reponse = await run_endpoint_function(
function_result = await run_endpoint_function(
dependant=dependent,
values=solved_result.values,
is_coroutine=is_coroutine,
)

content = await serialize_response(
response_content=raw_reponse,
response = ensure_response(function_result)

response.body = await serialize_response(
response_content=response.body,
field=response_field,
include=response_model_include,
exclude=response_model_exclude,
Expand All @@ -233,8 +236,8 @@ async def app(
is_coroutine=is_coroutine,
)

return content
return response

return None
raise AssertionError("unreachable")

return app
4 changes: 2 additions & 2 deletions faststream/nats/response.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import TYPE_CHECKING, Optional
from typing import TYPE_CHECKING, Dict, Optional

from typing_extensions import override

Expand All @@ -13,7 +13,7 @@ def __init__(
self,
body: "SendableMessage",
*,
headers: Optional["AnyDict"] = None,
headers: Optional[Dict[str, str]] = None,
correlation_id: Optional[str] = None,
stream: Optional[str] = None,
) -> None:
Expand Down
4 changes: 2 additions & 2 deletions faststream/nats/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
if TYPE_CHECKING:
from faststream.nats.publisher.asyncapi import AsyncAPIPublisher
from faststream.nats.subscriber.usecase import LogicSubscriber
from faststream.types import AnyDict, SendableMessage
from faststream.types import SendableMessage

__all__ = ("TestNatsBroker",)

Expand Down Expand Up @@ -187,7 +187,7 @@ def build_message(
*,
reply_to: str = "",
correlation_id: Optional[str] = None,
headers: Optional["AnyDict"] = None,
headers: Optional[Dict[str, str]] = None,
) -> "PatchedMessage":
msg, content_type = encode_message(message)
return PatchedMessage(
Expand Down
26 changes: 25 additions & 1 deletion tests/brokers/base/fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from fastapi.exceptions import RequestValidationError
from fastapi.testclient import TestClient

from faststream import context
from faststream import Response, context
from faststream.broker.core.usecase import BrokerUsecase
from faststream.broker.fastapi.context import Context
from faststream.broker.fastapi.router import StreamRouter
Expand Down Expand Up @@ -226,6 +226,30 @@ async def hello():
)
assert r == "hi", r

async def test_request(self, queue: str):
"""Local test due request exists in all TestClients."""
router = self.router_class(setup_state=False)

app = FastAPI()

args, kwargs = self.get_subscriber_params(queue)

@router.subscriber(*args, **kwargs)
async def hello():
return Response("Hi!", headers={"x-header": "test"})

async with self.broker_test(router.broker):
with TestClient(app) as client:
assert not client.app_state.get("broker")

r = await router.broker.request(
"hi",
queue,
timeout=0.5,
)
assert await r.decode() == "Hi!"
assert r.headers["x-header"] == "test"

async def test_base_without_state(self, queue: str):
router = self.router_class(setup_state=False)

Expand Down
Loading