python flask threaded true not working

Viewed 15610

With threaded=True requests are each handled in a new thread. But if I set threaded true to my application it is showing unknown behavior.

This is my code.

from flask import Flask
from flask import jsonify
import time

app = Flask("proxapp")

import datetime

@app.route('/slow')
def slow():
    start = datetime.datetime.now()
    time.sleep(10)
    return jsonify(start = start, end = datetime.datetime.now())


try:
    app.run(threaded=True)
except Exception, e:
    print repr(e)

I have opened two tabs in windows and tried to request same url in different tabs. second request is being served only after first request is being served. Second request is taking ~20 seconds to be served.

What is the problem with my code?

4 Answers

I cant seem to find my reference but I recall reading from another SO post why two tabs from the same browser fail when requesting form the same route despite threaded=True.

The gist of the post was that while threading will handle multiple connections to the same app better, the browser itself will try to reuse any already open connections. So with your two tab setup you could request from different routes and it work fine but if you request from the same route youll run into an issue because of the recycling of connections by the browser. Try opening two different browsers and testing this. Again I apologize for not having my original reference, I would like to give the author credit. If I find it Ill update this post.

Python's GIL allows only 1 thread to run at a time. So 2 requests will take 20 seconds in total. Whether they will run one at a time or interleave each other depends on many things, including the OS.

I found the most tricky problem! No matter what dubug server or production wsgi server you are using! When you are trying multi processes or multi threads! You should use different browsers or Chrome incognito window!!!!

solve all my problem! sample code here

from flask import Flask
import time
import os
import threading as td

app = Flask(__name__)

#trying  http://127.0.0.1:5000/
@app.route('/')
def index():
    print('index')
    print('pid:', os.getpid())
    print('thread id:', td.get_ident())
    time.sleep(10)
    return "Hello, World!"


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, threaded=True)
Related