因为业务需求需要使用websocket,所以在flask中使用websocket。在网上很多的资料,本文只记录我使用的方法。
首先是需要导入包
pip install gevent-websocket
导入包之后直接在项目中使用
from flask import Flask, request
from geventwebsocket.handler import WebSocketHandler #提供WS(websocket)协议处理
from geventwebsocket.server import WSGIServer #websocket服务承载
#WSGIServer导入的就是gevent.pywsgi中的类
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket
app = Flask(__name__)
clientList = []
@app.route("/")
def func():
client_socket = request.environ.get('wsgi.websocket')
if not client_socket:
return "error"
clientList.append(client_socket)
while 1:
for i in clientList:
try:
i.send(json.dumps(“111111”))
except Exception as e:
continue
if __name__ == '__main__':
http_server = WSGIServer(('127.0.0.1', 8888), application=app, handler_class=WebSocketHandler)
http_server.serve_forever()
其实使用比较简单,这里还是说一下我踩得几个坑吧:
1.在这个使用之后运行的时候尤其是pycharm运行的时候不要直接拿IDE的运行,而是使用命令行python app.py来运行,否则是直接运行flask项目,而不是使用下面的这种方式去启动项目。
2.因为在Gin框架中可以将get请求升级成websocket,这里也是同理。但是我之前想使用flask restful这个包,直接把get请求升级成websocket,但是那种方式是行不通的。现在还没有解决,如果有人成功了,可以在本文下留言到自己的博客地址供大家学习。非常感谢!
3.因为代码中有一个while 1,这导致在运行代码的时候会一直在这个请求里阻塞住,这个也是由于个人能力有限,只能把websocket这个接口单独拆出来做一个服务。当然这个在和很多业内的朋友讨论的时候也一致认为应该如此。但是如果有人解决,也请参考上一条,不胜感激!