Using FastStream with Django#
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. Itβs free and open source.
In this tutorial, let's see how to use the FastStream app alongside a Django app.
ASGI#
ASGI protocol supports lifespan events, and Django can be served as an ASGI application. So, the best way to integrate FastStream with the Django is by using ASGI lifespan. You can write it by yourself (it is really easy) or use something like this, but the preferred way for us is using Starlette Router.
Starlette Router allows you to serve any ASGI application you want, and it also supports lifespans. So, you can use it in your project to serve your regular Django ASGI and start up your FastStream broker too. Additionally, Starlette has much better static files support, providing an extra zero-cost feature.
Default Django Application#
Well, lets take a look at a default Django asgi.py
asgi.py | |
---|---|
You can already serve it using any ASGI server
For example, using uvicorn:
Or you can use Gunicorn with uvicorn workers
Your Django views, models and other stuff has no any changes if you serving it through ASGI, so you need no worry about it.
FastStream Integration#
Serving Django via Starlette#
Now, we need to modify our asgi.py
to serve it using Starlette
Serving static files with Starlette#
Also, Starlette has a better static files provider than original Django one, so we can reuse it too.
Just add this line to your settings.py
And collect all static files by default Django command
It creates a static/
directory in the root of your project, so you can serve it using Starlette
asgi.py | |
---|---|
FastStream lifespan#
Finally, we can add our FastStream integration like a regular lifespan
asgi.py | |
---|---|
Note
The code imports KafkaBroker
as our application is going to connect with Kafka. Depending on your requirements, import the necessary service's broker from the options provided by FastStream, such as RabbitBroker
, NatsBroker
or KafkaBroker
.
Full Example
This way we can easily integrate our FastStream application with the Django!