【问题标题】:Python websocket support on Azure web appservice?Azure web appservice 上的 Python websocket 支持?
【发布时间】:2017-09-12 07:54:09
【问题描述】:

Azure appservice 是否像 node.js/.net 一样具有适用于 Python 的本机 websocket?

我现在假设答案是否定的,您需要使用虚拟机来实现这一点吗?

(仅供参考。有一个类似的问题here,但已被删除。)

【问题讨论】:

    标签: python azure websocket real-time azure-web-app-service


    【解决方案1】:

    答案是肯定的,Azure Web Apps 上的 Python websocket 支持。必要的步骤或指南如下。

    1. 首先,您需要在Azure门户上启用Application settings到ON的WEB SOCKETS选项,如下blog所说,任何语言都可以。

    1. Azure IIS 支持使用 WSGI 的 Python webapp,您可以参考tutorial 了解它并按照教程内容使用 WSGI 构建和配置您的 Python webapp。

    2. 有一个类似的Combining websockets and WSGI in a python app SO 线程已经回答了关于在 Python 中使用 WSGI 的 websocket 的可行性。作为参考,有一些包支持这种组合,例如Eventlet,dwebsocket for Django等,您可以搜索词websocket和wsgi了解更多信息。

    希望对你有帮助。

    【讨论】:

    【解决方案2】:

    使用 Python 时,Linux 上的 Azure 应用服务默认使用 Gunicorn 作为所有传入请求的 Web 服务器。 WebSocket 连接以包含“升级”标头的特殊 HTTP GET 请求开始,服务器必须相应地处理该标头。有一些 WSGI 兼容的 WebSocket 库,在这个例子中我使用geventwebsocket

    首先,新建一个 Azure App Service Plan + Service:

    az appservice plan create -g <ResourceGroupName> -n MyAppPlan --is-linux --number-of-workers 4 --sku S1
    az webapp create -g <ResourceGroupName> -p MyAppPlan -n <AppServiceName> --runtime "PYTHON|3.7
    

    将以下示例保存到server.py:

    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    
    def websocket_app(environ, start_response):
        if environ["PATH_INFO"] == '/echo':
            ws = environ["wsgi.websocket"]
            while not ws.closed:
                message = ws.receive()
                ws.send(message)
    

    创建一个文件requirements.txt,内容如下

    gevent
    gevent-websocket
    

    创建一个文件.deployment,内容如下

    [config]
    SCM_DO_BUILD_DURING_DEPLOYMENT = true
    

    将所有三个文件放在一个 zip 文件夹 upload.zip 中并将其部署到 Azure

    az webapp deployment source config-zip -g <ResourceGroupName> -n <AppServiceName> --src upload.zip
    

    设置启动命令,我们在这里告诉 Gunicorn 使用 GeventWebSocketWorker 请求并在文件 server.py 中为应用程序提供服务,函数名称为 websocket_app。

    az webapp config set -g <ResourceGroupName> -n <AppServiceName> --startup-file "gunicorn --bind=0.0.0.0 -k "geventwebsocket.gunicorn.workers.GeventWebSocketWorker" server:websocket_app"
    

    在 Azure 中启用 WebSocket

    az webapp config set -g <ResourceGroupName> -n <AppServiceName> --web-sockets-enabled true
    

    启动后,您现在应该能够向服务器发送请求并获得回显响应(假设已安装 Python websockets 包 - pip install websockets)

    python -m websockets ws://<AppServiceName>.azurewebsites.net/echo
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      • 2012-12-27
      • 1970-01-01
      相关资源
      最近更新 更多