How to fix no route found error on Django Channels
Issue description Django Channels 對於不存在的路徑存取,全部會拋出錯誤,而不是一般性的警告處理,所以如果和我一樣在 Djangoo Channels 有裝上 Sentry ,而且伺服器在被惡意嘗試路徑時就會看到一堆 ValueError: No route found for path ‘…’. 的錯誤資訊,好處是知道被打了,壞處就是會噴錢(如果不是自己 Hosting)。
Fix it Make HandleRouteNotFoundMiddleware for this issue from datetime import datetime from logging import getLogger from django.urls.exceptions import Resolver404 logger = getLogger(file) class HandleRouteNotFoundMiddleware: def init(self, inner): self.inner = inner def call(self, scope): try: inner_instance = self.inner(scope) return inner_instance except (Resolver404, ValueError) as e: if 'No route found for path' not in str(e) and \ scope["type"] not in ['http', 'websocket']: raise e logger.