Run Python webserver -Flask- as a Websocket Client also
First let’s start by talking about the python webserver we’re using “Flask”. I will not talk about the details why I chose here (maybe in another blog). So Flask is a‘ microframework for Python based on Werkzeug, Jinja 2 and good intentions.’ . Its use and implementation is supper easy, as shown in the following example.
Lately, I was using it as a webserver, for receiving requests and processing some data into/from database. Everything was working perfectly, ‘till I had to add a Websocket client, that’s connecting to a Java websocket server.
To connect to any websocket server, python provides Websocket library that’s making everything easy for you.
You first define the basic events you will handle in your client:
Then, all what you need to do is running to the ws server :
Now, the problem is when you try to run both of them simultaneously, only one of them will be running. If you start first the websocket app, Flask app won’t be running, and if you do the opposite, only Flask app will be running.
The best solution I found, after checking different ones (that none of them actually worked), is to run them on different processes (Threads won’t work here cuz of the famous python GIL ).
All what you need to do is, put the running calls of both websocket app and flask app on different modules, then pass the methods as a target for two processes to run. And voila! both of them are working simultaneously without any issue !
I would be happy to answer any questions or comments you have :)