SoFunction
Updated on 2025-04-13

Django configuration implementation steps using asgi

1. Configuration prerequisites

Django version: Make sure to use Django 3.0+ (natively supported ASGI)

Necessary dependency

pip install daphne channels

2. Basic configuration steps

1. Create/modify ASGI entry file

In the Django project root directory (withSame level) Create

import os
from  import get_asgi_application
from  import ProtocolTypeRouter

('DJANGO_SETTINGS_MODULE', 'your_project.settings')

# Basic configuration (no WebSocket requirements)application = get_asgi_application()

# If using Channels (WebSocket support)application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AuthMiddlewareStack(
        URLRouter(
            your_app.routing.websocket_urlpatterns
        )
    ),
})

2. Modify project settings

Added in:

# Configure ASGI application pathASGI_APPLICATION = 'your_project.'

# If using Channels, you need to add itINSTALLED_APPS = [
    ...
    'channels',
    'your_app',
]

# Configure the channel layer (the development environment uses the memory layer)CHANNEL_LAYERS = {
    "default": {
        "BACKEND": ""
    }
}

3. Project structure verification

your_project/
├──           # ASGI entry file├── 
├── 
└── your_app/
    ├──    # WebSocket routing configuration (optional)    ...

3. Examples of configurations in different scenarios

Scenario 1: Pure HTTP service

# 
import os
from  import get_asgi_application

('DJANGO_SETTINGS_MODULE', 'your_project.settings')
application = get_asgi_application()

Scenario 2: WebSocket Service

  • Create a routing fileyour_app/
from  import path
from . import consumers

websocket_urlpatterns = [
    path('ws/chat/', .as_asgi()),
]
  • Revise
from  import AuthMiddlewareStack
from  import ProtocolTypeRouter, URLRouter
import your_app.routing

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AuthMiddlewareStack(
        URLRouter(
            your_app.routing.websocket_urlpatterns
        )
    ),
})

4. Operation and verification

1. Start using Daphne

daphne -b 0.0.0.0 -p 8000 your_project.asgi:application

2. Production environment deployment (Nginx + Daphne)

Example Nginx configuration:

location / {
    proxy_pass http://127.0.0.1:8000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_redirect off;
}

3. Test command

# Test HTTPcurl http://localhost:8000

# Test WebSocket (using wscat)wscat -c ws://localhost:8000/ws/chat/

5. Frequently Asked Questions

Error 1: You have not set ASGI_APPLICATION

• make sureCorrect configuration in:

ASGI_APPLICATION = 'your_project.'

Error 2: Requested setting INSTALLED_APPS...

• examineDJANGO_SETTINGS_MODULEAre the environment variables correctly set

Error 3: WebSocket connection failed

• verifyCHANNEL_LAYERSConfiguration
• Check whether Nginx is configured with WebSocket proxy

6. Advanced configuration

1. Use Redis channel layer (production environment)

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.",
        "CONFIG": {
            "hosts": [("redis-server", 6379)],
        },
    }
}

7. Key points to note

  • Development/production environment distinction: The channel layer configuration needs to be based on the environment
  • Performance monitoring:usedaphneof--verbosityParameter debugging
  • Version compatibility
    • Django 3.0+ native support for ASGI
    • Channels 3.0+ requires Python 3.6+

Through the above configuration, the Django project can fully support the ASGI protocol, which can not only handle traditional HTTP requests, but also support real-time WebSocket communication.

8. Write and start django+asgi

import os
from  import CommandLineInterface
import django
import subprocess
import sys


def main():
    base_path = ((__file__))
    # print("#"*30)
    # print(base_path)
    chat_ai_path = (base_path, 'xxx')
    (chat_ai_path)
    (base_path)
    # Set the default Django settings module    ("DJANGO_SETTINGS_MODULE", 'xxx')  # Replace with your project name    ()
    # Configure Daphne's running parameters     = [
        # "daphne",
        "-b", "0.0.0.0",
        "-p", "8000",
        ":application"
    ]
    CommandLineInterface().run()


if __name__ == "__main__":
    main()

This is the article about the implementation steps of using asgi for django configuration. For more related content on django configuration, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!