Files
hertz_django/hertz_server_django/asgi.py
2025-11-11 17:21:59 +08:00

50 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
ASGI config for hertz_server_django project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
from django.conf import settings
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hertz_server_django.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()
# Import websocket routing AFTER Django setup to avoid AppRegistryNotReady
from hertz_demo import routing as demo_routing
from hertz_studio_django_yolo import routing as yolo_routing
# Merge websocket routes
websocket_urlpatterns = (
demo_routing.websocket_urlpatterns +
yolo_routing.websocket_urlpatterns
)
# 在开发环境下放宽Origin校验便于第三方客户端如 Apifox、wscat调试
websocket_app = AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)
)
if getattr(settings, 'DEBUG', False):
application = ProtocolTypeRouter({
"http": django_asgi_app,
"websocket": websocket_app,
})
else:
application = ProtocolTypeRouter({
"http": django_asgi_app,
"websocket": AllowedHostsOriginValidator(websocket_app),
})