Last active
October 9, 2023 19:27
-
-
Save Lancetnik/a96ec29de76818934d84d45dc3726718 to your computer and use it in GitHub Desktop.
FastStream - Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from contextlib import asynccontextmanager | |
from django.core.asgi import get_asgi_application | |
from starlette.applications import Starlette | |
from starlette.routing import Mount | |
from starlette.staticfiles import StaticFiles | |
from faststream.nats import NatsBroker | |
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') | |
broker = NatsBroker() | |
@asynccontextmanager | |
async def broker_lifespan(app): | |
await broker.start() | |
try: | |
yield | |
finally: | |
await broker.close() | |
app = Starlette( | |
routes=( | |
Mount("/static", StaticFiles(directory="static"), name="static"), | |
Mount("/", get_asgi_application()), # regular Django ASGI | |
), | |
lifespan=broker_lifespan, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ASGI protocol supports lifespan events and Django could be served as an ASGI application as well. So, the better way to integrate FastStream with the Django is ASGI lifespans usage. You can write it by your own (it is really easy) or use smth like this, but the preffered way for me is a Starlette Router usage.
Startlette Router allows to serve any asgi application you want, also it supports lifespans too. So, you can use it in your project to serve your regular Django asgi and startup your FastStream broker too. Also, Starlette has a much better staticfiles support, so you have an extra zero-cost feature.
This router can be serve with any ASGI server in a regular way:
Gunicorn with uvicorn worker works fine too