我正在试验Flask-Sockets。过去添加了对蓝图的支持,这是我真正需要的。
from flask import Flask, request, abort, redirect, url_for, render_template, make_response, Response, jsonify, session
import json
#Importing blueprints
from play import play, play_socket
app = Flask(__name__)
sockets = Sockets(app)
app.register_blueprint(play, url_prefix=r"/play")
sockets.register_blueprint(play_socket, url_prefix=r"/play")
@sockets.route('/echo')
def echo_socket(ws):
while not ws.closed:
message = ws.receive()
response = json.dumps({"Message":message,"Response":"Message received"})
ws.send(response)
因此,在 JavaScript 中连接一个 websocket 并将端点设置为“echo”(即var ws = new WebSocket("ws://HOST:PORT/"+"echo")
)可以完美地工作。我可以发送消息,它们会立即退回给我。
但是,当我想将此函数移动到蓝图时(在蓝图中play_socket
,它不再起作用。假设我在 javascript 中将端点更改为“/status_ping”:
@play_socket.route('/status_ping')
def ping(ws):
while not ws.closed:
message = ws.receive()
response = json.dumps({"Message":message,"Response":"Message received"})
ws.send(response)
websocket 已从客户端成功连接,我可以通过print("HERE")
在def ping(socket):
.
我发现如果我将while not ws.closed:
循环体移动到标题上方(复制它),它就会“起作用”。但是,我不能使用它,因为我需要套接字将数据从服务器推送到客户端。执行此 while 循环时似乎出错了。由于某种原因,套接字立即关闭。更改while not ws.closed:
为while True:
没有效果。
我试图尽可能多地隔离问题,但如果您需要更多信息,请告诉我。
编辑:蓝图的代码示例
from flask import Flask, request, abort, redirect, url_for, render_template, make_response, Response, jsonify, session, current_app
import sys
sys.path.append('../')
from flask_sockets import Sockets
import json
import time
api_blueprint = Blueprint('api_blueprint', __name__)
@sockets.route('/update_status')
def echo_socket(ws):
message = ws.receive()
while not ws.closed:
ws.send(json.dumps({"data":message}))
time.sleep(1)
if ws.closed:
session.clear()
print("session cleared")
sockets = Sockets(current_app)
sockets.register_blueprint(api_blueprint, url_prefix=r"/api")
上下文可用的主run.py
文件以以下方式开始:app
if __name__ == "__main__":
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
server = pywsgi.WSGIServer(('0.0.0.0', 15080), app, handler_class=WebSocketHandler)
print(server)
server.serve_forever()