Wednesday, July 21, 2021

What is Daphne and use with Django

Daphne is a pure-Python ASGI server for UNIX, maintained by members of the Django project. It acts as the reference server for ASGI.

python -m pip install daphne


Running Django in Daphne

When Daphne is installed, a daphne command is available which starts the Daphne server process. At its simplest, Daphne needs to be called with the location of a module containing an ASGI application object, followed by what the application is called (separated by a colon).

For a typical Django project, invoking Daphne would look like:

daphne myproject.asgi:application

This will start one process listening on 127.0.0.1:8000. It requires that your project be on the Python path; to ensure that run this command from the same directory as your manage.py file.



Daphne is a HTTP, HTTP2 and WebSocket protocol server for ASGI and ASGI-HTTP, developed to power Django Channels.

It supports automatic negotiation of protocols; there's no need for URL prefixing to determine WebSocket endpoints versus HTTP endpoints.


Running

Simply point Daphne to your ASGI application, and optionally set a bind address and port (defaults to localhost, port 8000):

daphne -b 0.0.0.0 -p 8001 django_project.asgi:application

If you intend to run daphne behind a proxy server you can use UNIX sockets to communicate between the two:


daphne -u /tmp/daphne.sock django_project.asgi:application


If daphne is being run inside a process manager, you might want it to bind to a file descriptor passed down from a parent process. To achieve this you can use the --fd flag:

daphne --fd 5 django_project.asgi:application


If you want more control over the port/socket bindings you can fall back to using twisted's endpoint description strings by using the --endpoint (-e) flag, which can be used multiple times. This line would start a SSL server on port 443, assuming that key.pem and crt.pem exist in the current directory (requires pyopenssl to be installed):


daphne -e ssl:443:privateKey=key.pem:certKey=crt.pem django_project.asgi:application


Endpoints even let you use the txacme endpoint syntax to get automatic certificates from Let's Encrypt, which you can read more about at http://txacme.readthedocs.io/en/stable/.

To see all available command line options run daphne with the -h flag.



HTTP/2 Support


Daphne supports terminating HTTP/2 connections natively. You'll need to do a couple of things to get it working, though. First, you need to make sure you install the Twisted http2 and tls extras:

pip install -U 'Twisted[tls,http2]'

Next, because all current browsers only support HTTP/2 when using TLS, you will need to start Daphne with TLS turned on, which can be done using the Twisted endpoint syntax:

daphne -e ssl:443:privateKey=key.pem:certKey=crt.pem django_project.asgi:application





References:

https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/daphne/

No comments:

Post a Comment