|
1 | 1 | import logging |
| 2 | +from contextlib import asynccontextmanager |
2 | 3 | from typing import cast |
3 | 4 |
|
4 | 5 | from fastapi import FastAPI |
|
15 | 16 | _logger = logging.getLogger(__name__) |
16 | 17 |
|
17 | 18 |
|
18 | | -def setup(app: FastAPI) -> None: |
19 | | - async def on_startup() -> None: |
20 | | - with log_context( |
21 | | - _logger, |
22 | | - logging.INFO, |
23 | | - msg="Storage startup Rabbitmq", |
24 | | - ): |
25 | | - app.state.rabbitmq_client = None |
26 | | - rabbit_settings: RabbitSettings | None = app.state.settings.STORAGE_RABBITMQ |
27 | | - if not rabbit_settings: |
28 | | - raise ConfigurationError( |
29 | | - msg="RabbitMQ client is de-activated in the settings" |
30 | | - ) |
31 | | - await wait_till_rabbitmq_responsive(rabbit_settings.dsn) |
32 | | - app.state.rabbitmq_client = RabbitMQClient( |
33 | | - client_name="storage", settings=rabbit_settings |
| 19 | +@asynccontextmanager |
| 20 | +async def rabbitmq_lifespan(app: FastAPI): |
| 21 | + with log_context( |
| 22 | + _logger, |
| 23 | + logging.INFO, |
| 24 | + msg="Storage startup Rabbitmq", |
| 25 | + ): |
| 26 | + app.state.rabbitmq_client = None |
| 27 | + rabbit_settings: RabbitSettings | None = app.state.settings.STORAGE_RABBITMQ |
| 28 | + if not rabbit_settings: |
| 29 | + raise ConfigurationError( |
| 30 | + msg="RabbitMQ client is de-activated in the settings" |
34 | 31 | ) |
35 | | - app.state.rabbitmq_rpc_server = await RabbitMQRPCClient.create( |
36 | | - client_name="storage_rpc_server", settings=rabbit_settings |
37 | | - ) |
38 | | - |
39 | | - async def on_shutdown() -> None: |
40 | | - with log_context( |
41 | | - _logger, |
42 | | - logging.INFO, |
43 | | - msg="Storage shutdown Rabbitmq", |
44 | | - ): |
45 | | - if app.state.rabbitmq_client: |
46 | | - await app.state.rabbitmq_client.close() |
47 | | - if app.state.rabbitmq_rpc_server: |
48 | | - await app.state.rabbitmq_rpc_server.close() |
| 32 | + await wait_till_rabbitmq_responsive(rabbit_settings.dsn) |
| 33 | + app.state.rabbitmq_client = RabbitMQClient( |
| 34 | + client_name="storage", settings=rabbit_settings |
| 35 | + ) |
| 36 | + app.state.rabbitmq_rpc_server = await RabbitMQRPCClient.create( |
| 37 | + client_name="storage_rpc_server", settings=rabbit_settings |
| 38 | + ) |
49 | 39 |
|
50 | | - app.add_event_handler("startup", on_startup) |
51 | | - app.add_event_handler("shutdown", on_shutdown) |
| 40 | + yield |
| 41 | + |
| 42 | + with log_context( |
| 43 | + _logger, |
| 44 | + logging.INFO, |
| 45 | + msg="Storage shutdown Rabbitmq", |
| 46 | + ): |
| 47 | + if app.state.rabbitmq_client: |
| 48 | + await app.state.rabbitmq_client.close() |
| 49 | + if app.state.rabbitmq_rpc_server: |
| 50 | + await app.state.rabbitmq_rpc_server.close() |
52 | 51 |
|
53 | 52 |
|
54 | 53 | def get_rabbitmq_client(app: FastAPI) -> RabbitMQClient: |
|
0 commit comments