Python Azure 网络应用服务是否支持网络套接字?

Python websocket support on Azure web appservice?

A​​zure appservice 是否像 node.js/.net 一样为 Python 提供原生 websockets?

我现在假设,答案是否定的,您需要使用 VM 来实现吗?

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

答案是,Python Azure Web 应用程序支持 websocket。必要的步骤或指南如下。

  1. 首先,你需要在Azure portal上启用Application settingsONWEB SOCKETS选项,如下blog所说,与任何语言。

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

  2. Django等也有类似的Combining websockets and WSGI in a python app SO thread which had been answered about the feasibility for websocket with WSGI in Python. And as references, there are some packages supported this combination, such as Eventlet, dwebsocket可以搜索websocket&wsgi了解更多

希望对您有所帮助。

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

首先,创建一个新的 Azure 应用服务计划 + 服务:

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 中启用 WebSockets

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