使用flask + websocket来进行前后端交互的项目
前端发送send的时候,websocket一连接就中断,测试了心跳设置相应时间等各种方法,都没用,最后发现原来是flask的版本太高导致和gevent不兼容
无论前端怎么发送信息,flask的服务器端什么都没有:
服务器端代码:
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket # 引这个模块为了注释中显示提示用
from flask import Flask, render_template,request
app = Flask(__name__)
@app.route('/my_app')
def my_app():
return render_template('my_app.html')
@app.route('/my_ws')
def my_ws():
print(request.environ)
user_socket = request.environ.get('wsgi.websocket') # type:WebSocket
while 1:
msg = user_socket.receive()
print(msg)
user_socket.send(msg)
if __name__ == '__main__':
# app.run()
http_server = WSGIServer(('0.0.0.0',9527),app,handler_class=WebSocketHandler)
http_server.serve_forever()
前端客户端代码:
<body>
我即将是Websocket
</body>
<script>
var ws = new WebSocket("ws://127.0.0.1:9527/my_ws")
ws.onmessage = function (MessageEvent) {
console.log(MessageEvent.data);
}
</script>
前端调试的时候老是报错:
最后将flask一系列的包都降级后,错误消失:
解决流程:
一开始的flask 的版本是2点多
Flask 降级
pip install Flask==1.1.2
ImportError: cannot import name 'escape' from 'jinja2
pipuninstallJinja2
from flask) (1.1.0) Requirement already satisfied: Jinja2>=2.10.1
Pip install Jinja2==2.10.1
解决ImportError: cannot import name ‘soft_unicode‘ from ‘markupsafe‘
必须安装这个:pip install markupsafe==2.0.1
werkzeug 2.2.2 requires MarkupSafe>=2.1.1, but you have markupsafe 2.0.1 which is incompatible. 或者 ImportError: cannot import name 'json' from 'itsdangerous' (/Users/hyy/Desktop/项目/venv_37/lib/python3.7/site-packages/itsdangerous/init.py)
Pip install itsdangerous==2.0.1
ImportError: cannot import name 'BaseResponse' from 'werkzeug.wrappers' (/Users/hyy/Desktop/项目/venv_37/lib/python3.7/site-packages/werkzeug/wrappers/init.py)
Pip show werkzeug
Name: Werkzeug
Version: 2.2.2
继续降级:pip install werkzeug-1.0.1
Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
未捕获(在promise中)错误:侦听器返回true表示异步响应,但消息通道在收到响应之前关闭
关闭浏览器的所有插件,这大概率不是项目代码的问题,而是浏览器扩展的问题。曾经出现的异常就是因为我浏览器中安装的Tampermonkey扩展,把该扩展禁用了就可以了,就不会再报这个异常了。
版权归原作者 贝叶斯巴达 所有, 如有侵权,请联系我们删除。