Long Polling in Python with Flask -



Long Polling in Python with Flask -

i'm trying long polling jquery , python under flask framework.

having done long polling before in php, i've tried go in same way:

a script/function has while(true) loop, checking changes periodically eg.every 0,5 seconds in database, , returns info when alter occurs.

so in ini.py i've created app.route /poll jquery call. jquery gives info client's current state, , poll() function compares what's in database. loop ended , returns info when alter observed.

here's python code:

@app.route('/poll') def poll(): client_state = request.args.get("state") #remove html encoding + whitesapce client state html_parser = htmlparser.htmlparser() client_state = html_parser.unescape(client_state) client_state = "".join(client_state.split()) #poll database while true: time.sleep(0.5) info = get_data() json_state = to_json(data) json_state = "".join(data) #remove whitespace if json_state != client_state: homecoming "change"

the problem that, when code above starts polling, server appears overloaded , other ajax calls, , other requests loading "loading" image html using jquery unresponsive , timeout.

for completion's sake i've 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 alter has occurred"); } poll(); }, error: function(jqxhr, textstatus, errorthrown) { console.log(jqxhr.status + "," + textstatus + ", " + errorthrown); poll(); } }); }

does need multi-threaded or something? or have thought why i'm experiencing behavior?

thanks in advance!! :)

just link @robᵩ mentioned, flask app overload. that's because flask app in single threading mode default when running app.run(), can serve 1 request per time.

you can start multi threading with:

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

or using wsgi server gunicorn or uwsgi serve flask multi processing:

gunicorn -w 4 myapp:app

hopes you're enjoying python , flask!

python flask long-polling

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -