Skip to content

Instantly share code, notes, and snippets.

@Lancetnik
Last active October 9, 2023 19:27
Show Gist options
  • Save Lancetnik/a96ec29de76818934d84d45dc3726718 to your computer and use it in GitHub Desktop.
Save Lancetnik/a96ec29de76818934d84d45dc3726718 to your computer and use it in GitHub Desktop.
FastStream - Django
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,
)
@Lancetnik
Copy link
Author

Lancetnik commented Oct 9, 2023

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:

uvicorn run asgi:app

Gunicorn with uvicorn worker works fine too

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment