| 1 |
============================== |
| 2 |
How to use Django with Uvicorn |
| 3 |
============================== |
| 4 |
|
| 5 |
Uvicorn_ is an ASGI server based on ``uvloop`` and ``httptools``, with an |
| 6 |
emphasis on speed. |
| 7 |
|
| 8 |
Installing Uvicorn |
| 9 |
================== |
| 10 |
|
| 11 |
You can install Uvicorn with ``pip``: |
| 12 |
|
| 13 |
.. code-block:: shell |
| 14 |
|
| 15 |
python -m pip install uvicorn |
| 16 |
|
| 17 |
Running Django in Uvicorn |
| 18 |
========================= |
| 19 |
|
| 20 |
When Uvicorn is installed, a ``uvicorn`` command is available which runs ASGI |
| 21 |
applications. Uvicorn needs to be called with the location of a module |
| 22 |
containing an ASGI application object, followed by what the application is |
| 23 |
called (separated by a colon). |
| 24 |
|
| 25 |
For a typical Django project, invoking Uvicorn would look like: |
| 26 |
|
| 27 |
.. code-block:: shell |
| 28 |
|
| 29 |
python -m uvicorn myproject.asgi:application |
| 30 |
|
| 31 |
This will start one process listening on ``127.0.0.1:8000``. It requires that |
| 32 |
your project be on the Python path; to ensure that run this command from the |
| 33 |
same directory as your ``manage.py`` file. |
| 34 |
|
| 35 |
In development mode, you can add ``--reload`` to cause the server to reload any |
| 36 |
time a file is changed on disk. |
| 37 |
|
| 38 |
For more advanced usage, please read the `Uvicorn documentation <Uvicorn_>`_. |
| 39 |
|
| 40 |
Deploying Django using Uvicorn and Gunicorn |
| 41 |
=========================================== |
| 42 |
|
| 43 |
Gunicorn_ is a robust web server that implements process monitoring and automatic |
| 44 |
restarts. This can be useful when running Uvicorn in a production environment. |
| 45 |
|
| 46 |
To install Uvicorn and Gunicorn, use the following: |
| 47 |
|
| 48 |
.. code-block:: shell |
| 49 |
|
| 50 |
python -m pip install uvicorn uvicorn-worker gunicorn |
| 51 |
|
| 52 |
Then start Gunicorn using the Uvicorn worker class like this: |
| 53 |
|
| 54 |
.. code-block:: shell |
| 55 |
|
| 56 |
python -m gunicorn myproject.asgi:application -k uvicorn_worker.UvicornWorker |
| 57 |
|
| 58 |
.. _Uvicorn: https://www.uvicorn.org/ |
| 59 |
.. _Gunicorn: https://gunicorn.org/ |