Skip to content

AsgiFastStream

faststream.asgi.app.AsgiFastStream #

AsgiFastStream(
    *brokers: BrokerUsecase[Any, Any, Any],
    asgi_routes: Sequence[tuple[str, ASGIApp]] = (),
    logger: Optional[LoggerProto] = logger,
    provider: Provider | None = None,
    serializer: Optional[SerializerProto] = EMPTY,
    context: ContextRepo | None = None,
    lifespan: Optional[Lifespan] = None,
    on_startup: Sequence[AnyCallable] = (),
    after_startup: Sequence[AnyCallable] = (),
    on_shutdown: Sequence[AnyCallable] = (),
    after_shutdown: Sequence[AnyCallable] = (),
    specification: Optional[SpecificationFactory] = None,
    asyncapi_path: str | AsyncAPIRoute | None = None,
)

Bases: Application

Source code in faststream/asgi/app.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def __init__(
    self,
    *brokers: "BrokerUsecase[Any, Any, Any]",
    asgi_routes: Sequence[tuple[str, "ASGIApp"]] = (),
    logger: Optional["LoggerProto"] = logger,
    provider: Provider | None = None,
    serializer: Optional["SerializerProto"] = EMPTY,
    context: ContextRepo | None = None,
    lifespan: Optional["Lifespan"] = None,
    on_startup: Sequence["AnyCallable"] = (),
    after_startup: Sequence["AnyCallable"] = (),
    on_shutdown: Sequence["AnyCallable"] = (),
    after_shutdown: Sequence["AnyCallable"] = (),
    specification: Optional["SpecificationFactory"] = None,
    asyncapi_path: str | AsyncAPIRoute | None = None,
) -> None:
    self.routes = list(asgi_routes)

    super().__init__(
        *brokers,
        logger=logger,
        config=FastDependsConfig(
            provider=provider or dependency_provider,
            context=context or ContextRepo(),
            serializer=serializer,
        ),
        lifespan=lifespan,
        on_startup=on_startup,
        after_startup=after_startup,
        on_shutdown=on_shutdown,
        after_shutdown=after_shutdown,
        specification=specification,
    )

    if asyncapi_path:
        asyncapi_route = AsyncAPIRoute.ensure_route(asyncapi_path)
        handler = asyncapi_route(self.schema)
        handler.set_logger(logger)
        self.routes.append((asyncapi_route.path, handler))

        if asyncapi_route.asyncapi_json_path:

            @get(include_in_schema=asyncapi_route.include_in_schema)
            async def json_handler(scope: "Scope") -> AsgiResponse:  # noqa: ARG001
                return JSONResponse(self.schema.to_specification().to_jsonable())

            self.routes.append((asyncapi_route.asyncapi_json_path, json_handler))

        if asyncapi_route.try_it_out_path is not None and self.brokers:
            try_it_out_route = make_try_it_out_handler(
                self.brokers,
                include_in_schema=asyncapi_route.include_in_schema,
            )
            try_it_out_route.update_fd_config(self.config)
            try_it_out_route.set_logger(logger)

            self.routes.append((
                asyncapi_route.try_it_out_path,
                try_it_out_route,
            ))

    self._server = OuterRunState()

    self._log_level: int = logging.INFO
    self._run_extra_options: dict[str, SettingField] = {}

routes instance-attribute #

routes = list(asgi_routes)

context property #

context: ContextRepo

broker property #

broker: Optional[BrokerUsecase[Any, Any, Any]]

logger instance-attribute #

logger = logger

lifespan_context instance-attribute #

lifespan_context = apply_types(
    func=lifespan,
    serializer_cls=self.config._serializer,
    cast_result=False,
    context__=self.context,
)

from_app classmethod #

from_app(
    app: Application,
    asgi_routes: Sequence[tuple[str, ASGIApp]],
    asyncapi_path: str | AsyncAPIRoute | None = None,
) -> Self
Source code in faststream/asgi/app.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
@classmethod
def from_app(
    cls,
    app: Application,
    asgi_routes: Sequence[tuple[str, "ASGIApp"]],
    asyncapi_path: str | AsyncAPIRoute | None = None,
) -> Self:
    asgi_app = cls(
        *app.brokers,
        asgi_routes=asgi_routes,
        asyncapi_path=asyncapi_path,
        logger=app.logger,
        lifespan=None,
    )
    asgi_app.lifespan_context = app.lifespan_context
    asgi_app._on_startup_calling = app._on_startup_calling
    asgi_app._after_startup_calling = app._after_startup_calling
    asgi_app._on_shutdown_calling = app._on_shutdown_calling
    asgi_app._after_shutdown_calling = app._after_shutdown_calling
    return asgi_app

mount #

mount(path: str, route: ASGIApp) -> None
Source code in faststream/asgi/app.py
189
190
191
192
def mount(self, path: str, route: "ASGIApp") -> None:
    asgi_route = (path, route)
    self.routes.append(asgi_route)
    self._register_route(asgi_route)

run async #

run(
    log_level: int = INFO,
    run_extra_options: dict[str, SettingField]
    | None = None,
) -> None
Source code in faststream/asgi/app.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
async def run(
    self,
    log_level: int = logging.INFO,
    run_extra_options: dict[str, "SettingField"] | None = None,
) -> None:
    if not HAS_UVICORN:
        raise ImportError(INSTALL_UVICORN)

    self._log_level = log_level
    self._run_extra_options = cast_uvicorn_params(run_extra_options or {})

    config = uvicorn.Config(
        app=self,
        log_level=self._log_level,
        **{
            key: v
            for key, v in self._run_extra_options.items()
            if key in set(inspect.signature(uvicorn.Config).parameters.keys())
        },
    )

    server = uvicorn.Server(config)
    await server.serve()

exit #

exit() -> None

Manual stop method.

Source code in faststream/asgi/app.py
245
246
247
def exit(self) -> None:
    """Manual stop method."""
    self._server.stop()

start_lifespan_context async #

start_lifespan_context(
    run_extra_options: dict[str, SettingField]
    | None = None,
) -> AsyncGenerator[None, None]
Source code in faststream/asgi/app.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
@asynccontextmanager
async def start_lifespan_context(
    self,
    run_extra_options: dict[str, "SettingField"] | None = None,
) -> AsyncGenerator[None, None]:
    run_extra_options = run_extra_options or self._run_extra_options

    async with self.lifespan_context(**run_extra_options):
        try:
            async with anyio.create_task_group() as tg:
                await tg.start(self.__start, logging.INFO, run_extra_options)

                try:
                    yield
                finally:
                    await self._shutdown()
                    tg.cancel_scope.cancel()

        except ExceptionGroup as e:
            for ex in e.exceptions:
                raise ex from ex.__cause__

lifespan async #

lifespan(
    scope: Scope, receive: Receive, send: Send
) -> None

Handle ASGI lifespan messages to start and shutdown the app.

Source code in faststream/asgi/app.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
async def lifespan(self, scope: "Scope", receive: "Receive", send: "Send") -> None:
    """Handle ASGI lifespan messages to start and shutdown the app."""
    started = False
    await receive()  # handle `lifespan.startup` event

    async def process_exception(ex: BaseException) -> None:
        exc_text = traceback.format_exc()
        if started:
            await send({"type": "lifespan.shutdown.failed", "message": exc_text})
        else:
            await send({"type": "lifespan.startup.failed", "message": exc_text})
        raise ex

    try:
        async with self.start_lifespan_context():
            await send({"type": "lifespan.startup.complete"})
            started = True
            await receive()  # handle `lifespan.shutdown` event

    except StartupValidationError as startup_exc:
        # Process `on_startup` and `lifespan` missed extra options
        if HAS_TYPER:
            from faststream._internal.cli.utils.errors import draw_startup_errors

            draw_startup_errors(startup_exc)
            await send({"type": "lifespan.startup.failed", "message": ""})

        else:
            await process_exception(startup_exc)

    except BaseException as base_exc:
        await process_exception(base_exc)

    else:
        await send({"type": "lifespan.shutdown.complete"})

not_found async #

not_found(
    scope: Scope, receive: Receive, send: Send
) -> None
Source code in faststream/asgi/app.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
async def not_found(self, scope: "Scope", receive: "Receive", send: "Send") -> None:  # noqa: PLR6301
    not_found_msg = "Application doesn't support regular HTTP protocol."

    if scope["type"] == "websocket":
        websocket_close = WebSocketClose(
            code=1000,
            reason=not_found_msg,
        )
        await websocket_close(scope, receive, send)
        return

    response = AsgiResponse(
        body=not_found_msg.encode(),
        status_code=404,
    )

    await response(scope, receive, send)

set_broker #

set_broker(broker: BrokerUsecase[Any, Any, Any]) -> None

Set already existed App object broker.

Useful then you create/init broker in on_startup hook.

Source code in faststream/_internal/application.py
108
109
110
111
112
113
114
115
116
@deprecated(
    "This method is deprecated and will be removed in 0.8.0 Use `add_broker` instead."
)
def set_broker(self, broker: "BrokerUsecase[Any, Any, Any]") -> None:
    """Set already existed App object broker.

    Useful then you create/init broker in `on_startup` hook.
    """
    self.add_broker(broker)

add_broker #

add_broker(broker: BrokerUsecase[Any, Any, Any]) -> None
Source code in faststream/_internal/application.py
118
119
120
121
122
123
124
125
def add_broker(self, broker: "BrokerUsecase[Any, Any, Any]") -> None:
    if broker in self.brokers:
        msg = f"Broker {broker} is already added"
        raise SetupError(msg)

    self.brokers.append(broker)
    self.schema.add_broker(broker)
    broker._update_fd_config(self.config)

start async #

start(**run_extra_options: SettingField) -> None

Executes startup hooks and start broker.

Source code in faststream/_internal/application.py
219
220
221
222
223
224
225
async def start(
    self,
    **run_extra_options: "SettingField",
) -> None:
    """Executes startup hooks and start broker."""
    async with self._start_hooks_context(**run_extra_options):
        await self._start_broker()

stop async #

stop() -> None

Executes shutdown hooks and stop broker.

Source code in faststream/_internal/application.py
268
269
270
271
272
async def stop(self) -> None:
    """Executes shutdown hooks and stop broker."""
    async with self._shutdown_hooks_context():
        for broker in self.brokers:
            await broker.stop()

on_startup #

on_startup(
    func: Callable[P_HookParams, T_HookReturn],
) -> Callable[P_HookParams, T_HookReturn]

Add hook running BEFORE broker connected.

This hook also takes an extra CLI options as a kwargs.

Source code in faststream/_internal/application.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
def on_startup(
    self,
    func: Callable[P_HookParams, T_HookReturn],
) -> Callable[P_HookParams, T_HookReturn]:
    """Add hook running BEFORE broker connected.

    This hook also takes an extra CLI options as a kwargs.
    """
    self._on_startup_calling.append(
        apply_types(
            to_async(func),
            serializer_cls=self.config._serializer,
            context__=self.context,
        ),
    )
    return func

on_shutdown #

on_shutdown(
    func: Callable[P_HookParams, T_HookReturn],
) -> Callable[P_HookParams, T_HookReturn]

Add hook running BEFORE broker disconnected.

Source code in faststream/_internal/application.py
321
322
323
324
325
326
327
328
329
330
331
332
333
def on_shutdown(
    self,
    func: Callable[P_HookParams, T_HookReturn],
) -> Callable[P_HookParams, T_HookReturn]:
    """Add hook running BEFORE broker disconnected."""
    self._on_shutdown_calling.append(
        apply_types(
            to_async(func),
            serializer_cls=self.config._serializer,
            context__=self.context,
        ),
    )
    return func

after_startup #

after_startup(
    func: Callable[P_HookParams, T_HookReturn],
) -> Callable[P_HookParams, T_HookReturn]

Add hook running AFTER broker connected.

Source code in faststream/_internal/application.py
335
336
337
338
339
340
341
342
343
344
345
346
347
def after_startup(
    self,
    func: Callable[P_HookParams, T_HookReturn],
) -> Callable[P_HookParams, T_HookReturn]:
    """Add hook running AFTER broker connected."""
    self._after_startup_calling.append(
        apply_types(
            to_async(func),
            serializer_cls=self.config._serializer,
            context__=self.context,
        ),
    )
    return func

after_shutdown #

after_shutdown(
    func: Callable[P_HookParams, T_HookReturn],
) -> Callable[P_HookParams, T_HookReturn]

Add hook running AFTER broker disconnected.

Source code in faststream/_internal/application.py
349
350
351
352
353
354
355
356
357
358
359
360
361
def after_shutdown(
    self,
    func: Callable[P_HookParams, T_HookReturn],
) -> Callable[P_HookParams, T_HookReturn]:
    """Add hook running AFTER broker disconnected."""
    self._after_shutdown_calling.append(
        apply_types(
            to_async(func),
            serializer_cls=self.config._serializer,
            context__=self.context,
        ),
    )
    return func