我正在尝试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()
答案 0 :(得分:1)
你好Lennart Kloppenburg,
尝试将@play_socket.route('/status_ping')
蓝图路线放在sockets = Sockets(app)
之前。
以下对我有用,我可以在/ play / status_ping上与ping websocket交谈:
from flask import Blueprint, Flask, request, abort, redirect, url_for, render_template, make_response, Response, jsonify, session
from flask_sockets import Sockets
import json
play = Blueprint('simple_page', __name__)
play_socket = Blueprint('simple_page2', __name__)
@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)
app = Flask(__name__)
sockets = Sockets(app)
app.register_blueprint(play, url_prefix=r"/play")
sockets.register_blueprint(play_socket, url_prefix=r"/play")