問題描述
使用 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