Long flask poll in Python with a flask

I am trying to do a long poll using jQuery and Python under the framework jar.

After doing a long survey in PHP, I tried to do it the same way:

A script / function that has a while (true) loop, periodically checking for changes, for example, every 0.5 seconds in the database, and returns some data when changed.

So, in my ini .py, I created app.route for / poll to invoke jQuery. JQuery gives it some information about the current state of the client, and the poll () function compares this to what is currently in the database. The cycle is completed and returns information when a change is observed.

Here's the python code:

@app.route('/poll') def poll(): client_state = request.args.get("state") #remove html encoding + whitesapce from client state html_parser = HTMLParser.HTMLParser() client_state = html_parser.unescape(client_state) client_state = "".join(client_state.split()) #poll the database while True: time.sleep(0.5) data = get_data() json_state = to_json(data) json_state = "".join(data) #remove whitespace if json_state != client_state: return "CHANGE" 

The problem is that when the above code starts polling, the server becomes overloaded and other Ajax calls, and other requests, such as loading the “uploaded” image into html using jQuery, do not respond to requests and timeout.

For the full purpose, I have included jQuery here:

 function poll() { queryString = "state="+JSON.stringify(currentState); $.ajax({ url:"/poll", data: queryString, timeout: 60000, success: function(data) { console.log(data); if(currentState == null) { currentState = JSON.parse(data); } else { console.log("A change has occurred"); } poll(); }, error: function(jqXHR, textStatus, errorThrown) { console.log(jqXHR.status + "," + textStatus + ", " + errorThrown); poll(); } }); } 

Is it needed multithreaded or something like that? Or does anyone know why I experience this behavior?

Thanks in advance!:)

+6
source share
1 answer

Just like the @ Robᵩ link, the flash application is simply overloaded. This is because the jar application works by default in single-threaded mode when working with app.run() , so it can only serve one request per time.

You can start multithreading with:

 if __name__ == '__main__': app.run(threaded=True) 

Or using a WSGI server like gunicorn or uwsgi to serve a flask with multiprocessing:

 gunicorn -w 4 myapp:app 

I hope you enjoy Python and Flask!

+3
source

Source: https://habr.com/ru/post/984848/


All Articles