【Azure 应用服务】App Service for Linux 中实现 WebSocket 功能 (Python SocketIO)

简介: 【Azure 应用服务】App Service for Linux 中实现 WebSocket 功能 (Python SocketIO)

问题描述

使用 python websockets 模块作为Socket的服务端,发布到App Service for Linux环境后,发现Docker Container无法启动。错误消息为:

2021-10-28T02:39:51.812Z INFO  - docker run -d -p 1764:8000 --name test_0_c348bc62 -e WEBSITE_SITE_NAME=sockettest -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=sockettest.chinacloudsites.cn -e WEBSITE_INSTANCE_ID=08307498aa991c84523184617d17f074bad5139bd2c0710fdf2b1a0ad3d3a9b7 -e HTTP_LOGGING_ENABLED=1 appsvc/python:3.8_20210709.2 python socket_server.py 
2021-10-28T02:39:55.922Z INFO  - Initiating warmup request to container test_0_c348bc62 for site sockettest
2021-10-28T02:40:11.177Z INFO  - Waiting for response to warmup request for container test_0_c348bc62. Elapsed time = 15.2556084 sec
...
2021-10-28T02:43:33.439Z INFO  - Waiting for response to warmup request for container test_0_c348bc62. Elapsed time = 217.5175373 sec
2021-10-28T02:43:46.644Z ERROR - Container test_0_c348bc62 for site sockettest did not start within expected time limit. Elapsed time = 230.7221775 sec
2021-10-28T02:43:46.645Z ERROR - Container test_0_c348bc62 didn't respond to HTTP pings on port: 8000, failing site start. See container logs for debugging.
2021-10-28T02:43:46.672Z INFO  - Stopping site sockettest because it failed during startup.

PS:应用上云的需求。

 

问题解决

这是因为App Service Linux使用Container的启动需要Python代码中对HTTP进行正确的响应,否则Site无法启动。而这次的Python代码并不包含对HTTP请求的响应(需要Web框架),所以无法正确启动。

在Azure App Service for Linux - Python的文档中,主要介绍的两种Web框架为 Flask 和 Django。 接下来,就通过Flask 和SocketIO来实现WebSocket功能。

 

实现 Python SocketIO 代码及步骤

1)创建 app.py 文件,并复制以下内容,作为Socket的服务端及Flask应用的启动

from flask import Flask, render_template, session, copy_current_request_context
from flask_socketio import SocketIO, emit, disconnect
from threading import Lock
import os
async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()
## Used by App Service For linux
PORT = os.environ["PORT"] 
serverIP = "0.0.0.0"
# # Used by Local debug.
# PORT = 5000 
# serverIP = "127.0.0.1"
@app.route('/')
def index():
    return render_template('index.html', async_mode=socketio.async_mode)
@socketio.on('my_event', namespace='/test')
def test_message(message):
    print('receive message:' + message['data'],)
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': message['data'], 'count': session['receive_count']})
@socketio.on('my_broadcast_event', namespace='/test')
def test_broadcast_message(message):
    print('broadcast message:' + message['data'],)
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': message['data'], 'count': session['receive_count']},
         broadcast=True)
@socketio.on('disconnect_request', namespace='/test')
def disconnect_request():
    @copy_current_request_context
    def can_disconnect():
        disconnect()
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': 'Disconnected!', 'count': session['receive_count']},
         callback=can_disconnect)
if __name__ == '__main__':
    socketio.run(app,port=PORT, host=serverIP, debug=True)
    print('socket io start')

 

2)创建 template/index.html,并复制以下内容,作为Socket的客户端,验证WebSocket的正常工作

<!DOCTYPE HTML>
<html>
<head>
    <title>Socket-Test</title>
    <script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {
            namespace = '/test';
            var socket = io(namespace);
            socket.on('connect', function() {
                socket.emit('my_event', {data: 'connected to the SocketServer...'});
            });
            socket.on('my_response', function(msg, cb) {
                $('#log').append('<br>' + $('<div/>').text('logs #' + msg.count + ': ' + msg.data).html());
                if (cb)
                    cb();
            });
            $('form#emit').submit(function(event) {
                socket.emit('my_event', {data: $('#emit_data').val()});
                return false;
            });
            $('form#broadcast').submit(function(event) {
                socket.emit('my_broadcast_event', {data: $('#broadcast_data').val()});
                return false;
            });
            $('form#disconnect').submit(function(event) {
                socket.emit('disconnect_request');
                return false;
            });
        });
    </script>
</head>
<body style="background-color:white;">
    <h1 style="background-color:white;">Socket</h1>
    <form id="emit" method="POST" action='#'>
        <input type="text" name="emit_data" id="emit_data" placeholder="Message">
        <input type="submit" value="Send Message">
    </form>
    <form id="broadcast" method="POST" action='#'>
        <input type="text" name="broadcast_data" id="broadcast_data" placeholder="Message">
        <input type="submit" value="Send Broadcast Message">
    </form>
    <form id="disconnect" method="POST" action="#">
        <input type="submit" value="Disconnect Server">
    </form>
    <h2 style="background-color:white;">Logs</h2>
    <div id="log" ></div>
</body>
</html>

 

3)创建 requirements.txt 文件,并包含以下module及版本,如果版本不适合,可以适当修改。

Flask==1.0.2
Flask-Login==0.4.1
Flask-Session==0.3.1
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.0
six==1.11.0
Werkzeug==0.14.1
Flask-SocketIO==4.3.1
python-engineio==3.13.2
python-socketio==4.6.0
eventlet==0.30.2

以上三个就是整个项目的源文件,VS Code中的文件结构为:

 

 

4)在VS Code中使用az webapp up来部署Python Web应用

#设置登录环境为中国区Azure
az cloud set -n AzureChinaCloud
az login
#部署代码,如果pythonlinuxwebsocket01不存在,则自动创建定价层位B1的App Service
az webapp up --sku B1 --name pythonlinuxwebsocket01

效果展示:

 

5)修改App Service的启动命令

gunicorn --worker-class eventlet -w 1 app:app

注:为了避免 flask-socketIO 服务器部署 400 Bad Request 问题,所以需要使用 eventlet 作为工作进程。详细说明可见:https://blog.csdn.net/weixin_43958804/article/details/109024348

 

6)  开启WebSocket, 启用HTTP,  设置PORT参数

注:修改后,重启App Service。如果重启后使用HTTP请求,但是发生了302跳转到HTTPS的情况,就可以考虑重新部署一次站点。使用第四步方法,az webapp up然container重新生成项目信息。

7)验证Web Socket

使用HTTP访问刚刚部署的App Service URL。

 

 

 

附录一:解决flask-socketIO 服务器部署 400 Bad Request 问题

使用eventlet,设置启动命令:gunicorn --worker-class eventlet -w 1 app:app

 

附录二:Gunicorn ImportError: cannot import name 'ALREADY_HANDLED' from 'eventlet.wsgi' in docker

Installing older version of eventlet solved the problem: pip install eventlet==0.30.2

 

参考资料:

Implement a WebSocket Using Flask and Socket-IO(Python): https://medium.com/swlh/implement-a-websocket-using-flask-and-socket-io-python-76afa5bbeae1

解决flask-socketIO 服务器部署 400 Bad Request 问题:https://blog.csdn.net/weixin_43958804/article/details/109024348

相关文章
|
11月前
|
存储 安全 Linux
【Azure App Service】在App Service中查看CA证书
在 Azure App Service 中,使用自签名或私有 CA 证书的远程服务可能会导致 SSL 握手失败。解决方法包括使用受信任 CA 签发的证书,或通过 App Service Environment 加载自定义根证书,实现安全连接。
244 4
|
9月前
|
Java 应用服务中间件 API
【App Service】部署War包到Azure云上遇404错误
Java应用部署至Azure App Service for Windows后报404,本地运行正常。经排查,日志提示类文件版本不兼容:应用由Java 17(class file version 61.0)编译,但环境仅支持到Java 11(55.0)。错误根源为Java版本不匹配。调整App Service的Java版本至17后问题解决,成功访问接口。
1077 3
|
9月前
|
存储 Linux 网络安全
【Azure App Service】Root CA on App Service
Azure App Service for Windows应用连接外部SSL服务时,需确保其证书由受信任的根CA颁发。多租户环境下无法修改根证书,但ASE(单租户)可加载自定义CA证书。若遇证书信任问题,可更换为公共CA证书或将应用部署于ASE并导入私有CA证书。通过Kudu的PowerShell(Windows)或SSH(Linux)可查看当前受信任的根证书列表。
211 13
|
10月前
|
API 网络架构 容器
【Azure Container App】查看当前 Container App Environment 中的 CPU 使用情况的API
在扩展 Azure Container Apps 副本时,因 Container App Environment 的 CPU 核心数已达上限(500 cores),导致扩展失败。本文介绍如何使用 `az rest` 命令调用 Azure China Cloud 管理 API,查询当前环境的 CPU 使用情况,并提供具体操作步骤及示例。
356 17
|
10月前
|
网络协议 Java Linux
【App Service】在Azure环境中如何查看App Service实例当前的网络连接情况呢?
在 Azure App Service(Windows 和 Linux)中部署应用时,分析网络连接状态是排查异常、验证端口监听及确认后端连接的关键。本文介绍如何在 Linux 环境中使用 `netstat` 命令查看特定端口(如 443、3306、6380)的连接情况,并解析输出结果。同时说明在 Windows App Service 中 `netstat` 被禁用的情况下,如何通过门户抓包等替代方法进行网络诊断。内容涵盖命令示例、操作步骤及附录说明,帮助开发者快速掌握云环境中的网络分析技巧。
253 11
|
10月前
|
数据安全/隐私保护
【Azure Function App】PowerShell Function 执行 Get-AzAccessToken 的返回值类型问题:System.String 与 System.Security.SecureString
将PowerShell Function部署到Azure Function App后,Get-AzAccessToken返回值类型在不同环境中有差异。正常为SecureString类型,但部分情况下为System.String类型,导致后续处理出错。解决方法是在profile.ps1中设置环境变量$env:AZUREPS_OUTPUT_PLAINTEXT_AZACCESSTOKEN=false,以禁用明文输出。
250 1
|
11月前
|
数据采集 数据可视化 API
驱动业务决策:基于Python的App用户行为分析与可视化方案
驱动业务决策:基于Python的App用户行为分析与可视化方案
|
11月前
|
JSON JavaScript API
Python模拟HTTP请求实现APP自动签到
Python模拟HTTP请求实现APP自动签到
|
Linux Python
【Python】300行代码实现crontab定时器功能 【上】
熟悉Linux的都知道在Linux下有一个crontab的定时任务,可以很方便的进行各种定时、计划任务的执行。有时候写代码也需要用到定时器业务,因此我使用Python实现了一个类似的定时器模块,可以很方便的做定时业务,使用例子如下:
627 0
【Python】300行代码实现crontab定时器功能 【上】
|
Python
使用python实现一个文件搜索功能,类似于Everything功能
一般人日常总是会将一些片段信息记录到文件中,放到电脑硬盘上。等过段时间,可能就不知道放到哪里了,电脑上文件夹太多。 找文件一般都会借助于搜索软件,比如Everything软件就很强大,输入名称,就能全局查找文件;
916 0

热门文章

最新文章