带有 Django Channels 和 IIS 的 Websocket - 找不到路径的路由

问题描述 投票:0回答:1

我正在尝试将我的 Django 应用程序部署到我的 IIS 服务器,但我的 websocket 在通过 IIS 访问时不起作用,只能在本地运行。我错过了什么?

当我通过IIS访问时:

new WebSocket('ws://server:8000/ws/notificacoes') -> error 1006 
Log: ValueError: No route found for path 'ws/notificacoes'

当我通过 python runserver 访问时:

new WebSocket('ws://http://127.0.0.1:8000/ws/notificacoes') -> connected
Log: WebSocket HANDSHAKING /ws/notificacoes [127.0.0.1:53541]
WebSocket CONNECT /ws/notificacoes [127.0.0.1:53541]

消费者.py

class NotificacaoConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_group_name = 'notificacoes'

        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    async def notificacao_update(self, event):
        await self.send(text_data=json.dumps({
            'message': 'Notificação atualizada!'
        }))

路由.py

websocket_urlpatterns = [
    ...
    path('ws/notificacoes', NotificacaoConsumer.as_asgi(), name='notificacao'),
]

asgi.py

from index.routing import websocket_urlpatterns
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "web.settings")
django_asgi_app = get_asgi_application()

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
        ),
    }
)

编辑:这是我配置了反向代理的 web.config 文件。 Django Channels 在端口 8002 上运行 Daphne

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appSettings>
        <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" />
        <add key="PYTHONPATH" value="" />
        <add key="DJANGO_SETTINGS_MODULE" value="web.settings" />
        <add key="WSGI_LOG" value="logs\wfastcgi.log" />
    </appSettings>
    <system.webServer>
    <httpErrors errorMode="Detailed" />
    <handlers>
        <remove name="WebDAV" />
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <add name="Django Handler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python\python.exe|C:\Python\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,DELETE" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" />
    </handlers>
        <modules>
            <remove name="WebDAVModule" />
        </modules>
        <tracing>
            <traceFailedRequests>
                <add path="*">
                    <traceAreas>
                        <add provider="ASP" verbosity="Verbose" />
                        <add provider="ASPNET" areas="Infrastructure,Module,Page,AppServices" verbosity="Verbose" />
                        <add provider="ISAPI Extension" verbosity="Verbose" />
                        <add provider="WWW Server" areas="Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,FastCGI,WebSocket" verbosity="Verbose" />
                    </traceAreas>
                    <failureDefinitions statusCodes="500" verbosity="Warning" />
                </add>
            </traceFailedRequests>
        </tracing>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
            </customHeaders>
        </httpProtocol>
        <rewrite>
            <rules>
                <!-- Reverse proxy for Daphne running on 8002 -->
                <rule name="WebSocket Proxy" patternSyntax="Wildcard" stopProcessing="true">
                    <match url="ws*" />
                    <conditions>
                        <add input="{HTTP_CONNECT}" pattern="*" />
                    </conditions>
                    <action type="Rewrite" url="http://localhost:8002/{R:0}" logRewrittenUrl="true" />
                    <serverVariables>
                        <set name="HTTP_SEC_WEBSOCKET_EXTENSIONS" value="" />
                    </serverVariables>
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

python django iis websocket django-channels
1个回答
0
投票

按照 Lex Li 的建议,我禁用了压缩,重新启动了所有相关服务,它按预期工作了。

© www.soinside.com 2019 - 2024. All rights reserved.