Run Python webserver -Flask- as a Websocket Client also

Dhia Kennouche
Apr 5, 2019 · 2 min read

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.

Image for post
Image for post

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:

Image for post
Image for post

Then, all what you need to do is running to the ws server :

Image for post
Image for post

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 !

Image for post
Image for post

I would be happy to answer any questions or comments you have :)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store