Skip to content

Commit 905638f

Browse files
authored
Updateted lifespan setup. (#215)
Signed-off-by: Pavel Kirilin <[email protected]>
1 parent ec5f725 commit 905638f

File tree

7 files changed

+69
-88
lines changed

7 files changed

+69
-88
lines changed

fastapi_template/template/{{cookiecutter.project_name}}/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ $ tree "{{cookiecutter.project_name}}"
6363
├── api # Package with all handlers.
6464
│   └── router.py # Main router.
6565
├── application.py # FastAPI application configuration.
66-
└── lifetime.py # Contains actions to perform on startup and shutdown.
66+
└── lifespan.py # Contains actions to perform on startup and shutdown.
6767
```
6868
6969
## Configuration

fastapi_template/template/{{cookiecutter.project_name}}/tests/conftest.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,14 @@
2222
from aio_pika.pool import Pool
2323
from {{cookiecutter.project_name}}.services.rabbit.dependencies import \
2424
get_rmq_channel_pool
25-
from {{cookiecutter.project_name}}.services.rabbit.lifetime import (init_rabbit,
25+
from {{cookiecutter.project_name}}.services.rabbit.lifespan import (init_rabbit,
2626
shutdown_rabbit)
2727

2828
{%- endif %}
2929
{%- if cookiecutter.enable_kafka == "True" %}
3030
from aiokafka import AIOKafkaProducer
3131
from {{cookiecutter.project_name}}.services.kafka.dependencies import get_kafka_producer
32-
from {{cookiecutter.project_name}}.services.kafka.lifetime import (init_kafka,
32+
from {{cookiecutter.project_name}}.services.kafka.lifespan import (init_kafka,
3333
shutdown_kafka)
3434

3535
{%- endif %}

fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/services/kafka/lifetime.py renamed to fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/services/kafka/lifespan.py

File renamed without changes.

fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/services/rabbit/lifetime.py renamed to fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/services/rabbit/lifespan.py

File renamed without changes.

fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/services/redis/lifetime.py renamed to fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/services/redis/lifespan.py

File renamed without changes.

fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/web/application.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
{%- endif %}
1212
from importlib import metadata
1313

14-
from {{cookiecutter.project_name}}.web.lifetime import (register_shutdown_event,
15-
register_startup_event)
14+
from {{cookiecutter.project_name}}.web.lifespan import lifespan_setup
1615

1716
{%- if cookiecutter.orm == 'tortoise' %}
1817
from tortoise.contrib.fastapi import register_tortoise
@@ -80,6 +79,7 @@ def get_app() -> FastAPI:
8079
app = FastAPI(
8180
title="{{cookiecutter.project_name}}",
8281
version=metadata.version("{{cookiecutter.project_name}}"),
82+
lifespan=lifespan_setup,
8383
{%- if cookiecutter.self_hosted_swagger == 'True' %}
8484
docs_url=None,
8585
redoc_url=None,
@@ -91,10 +91,6 @@ def get_app() -> FastAPI:
9191
default_response_class=UJSONResponse,
9292
)
9393

94-
# Adds startup and shutdown events.
95-
register_startup_event(app)
96-
register_shutdown_event(app)
97-
9894
# Main router for the API.
9995
app.include_router(router=api_router, prefix="/api")
10096
{%- if cookiecutter.api_type == 'graphql' %}

fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/web/lifetime.py renamed to fastapi_template/template/{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/web/lifespan.py

Lines changed: 64 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
2-
from typing import Awaitable, Callable
2+
from typing import AsyncGenerator, Awaitable, Callable
3+
from contextlib import asynccontextmanager
34

45
from fastapi import FastAPI
56
from {{cookiecutter.project_name}}.settings import settings
@@ -11,19 +12,19 @@
1112
{%- endif %}
1213

1314
{%- if cookiecutter.enable_redis == "True" %}
14-
from {{cookiecutter.project_name}}.services.redis.lifetime import (init_redis,
15+
from {{cookiecutter.project_name}}.services.redis.lifespan import (init_redis,
1516
shutdown_redis)
1617

1718
{%- endif %}
1819

1920
{%- if cookiecutter.enable_rmq == "True" %}
20-
from {{cookiecutter.project_name}}.services.rabbit.lifetime import (init_rabbit,
21+
from {{cookiecutter.project_name}}.services.rabbit.lifespan import (init_rabbit,
2122
shutdown_rabbit)
2223

2324
{%- endif %}
2425

2526
{%- if cookiecutter.enable_kafka == "True" %}
26-
from {{cookiecutter.project_name}}.services.kafka.lifetime import (init_kafka,
27+
from {{cookiecutter.project_name}}.services.kafka.lifespan import (init_kafka,
2728
shutdown_kafka)
2829

2930
{%- endif %}
@@ -267,7 +268,8 @@ def setup_prometheus(app: FastAPI) -> None: # pragma: no cover
267268
{%- endif %}
268269

269270

270-
def register_startup_event(app: FastAPI) -> Callable[[], Awaitable[None]]: # pragma: no cover
271+
@asynccontextmanager
272+
async def lifespan_setup(app: FastAPI) -> AsyncGenerator[None, None]: # pragma: no cover
271273
"""
272274
Actions to run on application startup.
273275
@@ -278,79 +280,62 @@ def register_startup_event(app: FastAPI) -> Callable[[], Awaitable[None]]: # pr
278280
:return: function that actually performs actions.
279281
"""
280282

281-
@app.on_event("startup")
282-
async def _startup() -> None: # noqa: WPS430
283-
app.middleware_stack = None
284-
{%- if cookiecutter.enable_taskiq == "True" %}
285-
if not broker.is_worker_process:
286-
await broker.startup()
287-
{%- endif %}
288-
{%- if cookiecutter.orm == "sqlalchemy" %}
289-
_setup_db(app)
290-
{%- elif cookiecutter.orm == "ormar" %}
291-
await database.connect()
292-
{%- elif cookiecutter.orm in ["beanie", "psycopg"] %}
293-
await _setup_db(app)
294-
{%- endif %}
295-
{%- if cookiecutter.db_info.name != "none" and cookiecutter.enable_migrations != "True" %}
296-
{%- if cookiecutter.orm in ["ormar", "sqlalchemy"] %}
297-
await _create_tables()
298-
{%- endif %}
299-
{%- endif %}
300-
{%- if cookiecutter.otlp_enabled == "True" %}
301-
setup_opentelemetry(app)
302-
{%- endif %}
303-
{%- if cookiecutter.enable_redis == "True" %}
304-
init_redis(app)
305-
{%- endif %}
306-
{%- if cookiecutter.enable_rmq == "True" %}
307-
init_rabbit(app)
308-
{%- endif %}
309-
{%- if cookiecutter.enable_kafka == "True" %}
310-
await init_kafka(app)
311-
{%- endif %}
312-
{%- if cookiecutter.prometheus_enabled == "True" %}
313-
setup_prometheus(app)
314-
{%- endif %}
315-
app.middleware_stack = app.build_middleware_stack()
316-
pass # noqa: WPS420
317-
318-
return _startup
319-
320-
321-
def register_shutdown_event(app: FastAPI) -> Callable[[], Awaitable[None]]: # pragma: no cover
322-
"""
323-
Actions to run on application's shutdown.
324-
325-
:param app: fastAPI application.
326-
:return: function that actually performs actions.
327-
"""
283+
app.middleware_stack = None
284+
{%- if cookiecutter.enable_taskiq == "True" %}
285+
if not broker.is_worker_process:
286+
await broker.startup()
287+
{%- endif %}
288+
{%- if cookiecutter.orm == "sqlalchemy" %}
289+
_setup_db(app)
290+
{%- elif cookiecutter.orm == "ormar" %}
291+
await database.connect()
292+
{%- elif cookiecutter.orm in ["beanie", "psycopg"] %}
293+
await _setup_db(app)
294+
{%- endif %}
295+
{%- if cookiecutter.db_info.name != "none" and cookiecutter.enable_migrations != "True" %}
296+
{%- if cookiecutter.orm in ["ormar", "sqlalchemy"] %}
297+
await _create_tables()
298+
{%- endif %}
299+
{%- endif %}
300+
{%- if cookiecutter.otlp_enabled == "True" %}
301+
setup_opentelemetry(app)
302+
{%- endif %}
303+
{%- if cookiecutter.enable_redis == "True" %}
304+
init_redis(app)
305+
{%- endif %}
306+
{%- if cookiecutter.enable_rmq == "True" %}
307+
init_rabbit(app)
308+
{%- endif %}
309+
{%- if cookiecutter.enable_kafka == "True" %}
310+
await init_kafka(app)
311+
{%- endif %}
312+
{%- if cookiecutter.prometheus_enabled == "True" %}
313+
setup_prometheus(app)
314+
{%- endif %}
315+
app.middleware_stack = app.build_middleware_stack()
328316

329-
@app.on_event("shutdown")
330-
async def _shutdown() -> None: # noqa: WPS430
331-
{%- if cookiecutter.enable_taskiq == "True" %}
332-
if not broker.is_worker_process:
333-
await broker.shutdown()
334-
{%- endif %}
335-
{%- if cookiecutter.orm == "sqlalchemy" %}
336-
await app.state.db_engine.dispose()
337-
{% elif cookiecutter.orm == "ormar" %}
338-
await database.disconnect()
339-
{%- elif cookiecutter.orm == "psycopg" %}
340-
await app.state.db_pool.close()
341-
{%- endif %}
342-
{%- if cookiecutter.enable_redis == "True" %}
343-
await shutdown_redis(app)
344-
{%- endif %}
345-
{%- if cookiecutter.enable_rmq == "True" %}
346-
await shutdown_rabbit(app)
347-
{%- endif %}
348-
{%- if cookiecutter.enable_kafka == "True" %}
349-
await shutdown_kafka(app)
350-
{%- endif %}
351-
{%- if cookiecutter.otlp_enabled == "True" %}
352-
stop_opentelemetry(app)
353-
{%- endif %}
354-
pass # noqa: WPS420
317+
yield
355318

356-
return _shutdown
319+
{%- if cookiecutter.enable_taskiq == "True" %}
320+
if not broker.is_worker_process:
321+
await broker.shutdown()
322+
{%- endif %}
323+
{%- if cookiecutter.orm == "sqlalchemy" %}
324+
await app.state.db_engine.dispose()
325+
{% elif cookiecutter.orm == "ormar" %}
326+
await database.disconnect()
327+
{%- elif cookiecutter.orm == "psycopg" %}
328+
await app.state.db_pool.close()
329+
{%- endif %}
330+
{%- if cookiecutter.enable_redis == "True" %}
331+
await shutdown_redis(app)
332+
{%- endif %}
333+
{%- if cookiecutter.enable_rmq == "True" %}
334+
await shutdown_rabbit(app)
335+
{%- endif %}
336+
{%- if cookiecutter.enable_kafka == "True" %}
337+
await shutdown_kafka(app)
338+
{%- endif %}
339+
{%- if cookiecutter.otlp_enabled == "True" %}
340+
stop_opentelemetry(app)
341+
{%- endif %}

0 commit comments

Comments
 (0)