Because business needs require the use of websocket, so use websocket in the flask. In a lot of information online, this article only recording method I use.
The first is the need to import the package
pip install peddled-WebSocket
After importing the package used directly in the project
from flask import Flask, request from geventwebsocket.handler import WebSocketHandler # provide WS (websocket) protocol processing from geventwebsocket.server import WSGIServer #websocket bearer service #WSGIServer is introduced in class 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()
In fact, the use of relatively simple, there is still talk about it I stepped on a few pit:
1. When used in this run after run, especially pycharm when not directly take the IDE runs, but using the command line python app.py to run, otherwise it is run directly flask project, instead of using the following in this way to go Startup project.
Gin frame 2. Because the request can be upgraded to get websocket, is the same reason here. But before I want to use this package flask restful directly to get the request to upgrade to websocket, but does not work that way. Now it is not resolved, if someone is successful, you can shout to your blog address for them to learn in this article. thank you very much!
3. Because the code in a while 1, which leads to the code at run time would have been blocked at the request live in, this is due to limited personal capacity, only to split this single interface to websocket out to do a service. Of course, this time in the industry and many friends also agreed that the discussion should be so. But if someone is resolved, please refer to the one, be grateful!