File: asgi_example.rst

package info (click to toggle)
python-django-channels 4.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,036 kB
  • sloc: python: 3,109; makefile: 155; javascript: 60; sh: 8
file content (31 lines) | stat: -rw-r--r-- 1,115 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
.. code-block:: python

    import os

    from channels.auth import AuthMiddlewareStack
    from channels.routing import ProtocolTypeRouter, URLRouter
    from channels.security.websocket import AllowedHostsOriginValidator
    from django.core.asgi import get_asgi_application
    from django.urls import path

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
    # Initialize Django ASGI application early to ensure the AppRegistry
    # is populated before importing code that may import ORM models.
    django_asgi_app = get_asgi_application()

    from chat.consumers import AdminChatConsumer, PublicChatConsumer

    application = ProtocolTypeRouter({
        # Django's ASGI application to handle traditional HTTP requests
        "http": django_asgi_app,

        # WebSocket chat handler
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(
                URLRouter([
                    path("chat/admin/", AdminChatConsumer.as_asgi()),
                    path("chat/", PublicChatConsumer.as_asgi()),
                ])
            )
        ),
    })