Deny HTTP requests (ws only server) #1872
-
Say I want to have setup where I handle http requests with gunicorn and websocket related stuff with daphne (each in different containers). It seems that daphne can switch/fallback into http requests using the asgi app entry; I'm looking to change this behavior since I only want this server to handle websocket requests. Is it possible to deny HTTP requests in this case? Does this make sense to you? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Ideally your load-balancer (nginx for example) correctly routes the different request types to the correct app. You could though define an As of v3 ProtocolTypeRouter defines a default I hope that helps. |
Beta Was this translation helpful? Give feedback.
-
I couldn't configure nginx not to allow HTTP requests to the WS backend and I kept getting the This is import os
from channels.routing import ProtocolTypeRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django import setup
from django.conf import settings
from django.core.handlers.asgi import ASGIHandler
from django.http.response import HttpResponsePermanentRedirect
# This needs to be run first before imports from the project can be done
setup()
from yourproject.routing import ws_urls # noqa: E402
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yourproject.settings')
application_mapping = dict(
websocket=AllowedHostsOriginValidator(application=ws_urls))
if settings.DEBUG:
from django.core.asgi import get_asgi_application
http_handler = get_asgi_application()
application_mapping.update(http=http_handler) # type: ignore
else:
class RedirectAllHandler(ASGIHandler):
async def get_response_async(self, request):
return HttpResponsePermanentRedirect(redirect_to='/')
application_mapping.update(http=RedirectAllHandler()) # type: ignore
application = ProtocolTypeRouter(application_mapping=application_mapping) You're all welcome. |
Beta Was this translation helpful? Give feedback.
Ideally your load-balancer (nginx for example) correctly routes the different request types to the correct app.
You could though define an
http
handler in a ProtocolTypeRouter in order to reject any HTTP requests that did arrive.As of v3 ProtocolTypeRouter defines a default
http
handler if you don't provide one, but will not do that from v4 (next main version) — so HTTP requests would result in aValueError
, that would get converted to 500 — so you might want to define a dummy 4xx type handler if you think such requests may arrive at your application.I hope that helps.