4

Consider the following minimal working flask app:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "I am /"

@app.route("/api")
def api():
    return "I am /api"

if __name__ == "__main__":
    app.run()

This happily works. But when I try to make a GET request with the "requests" module from the hello route to the api route - I never get a response in the browser when trying to access http://127.0.0.1:5000/

from flask import Flask
import requests

app = Flask(__name__)

@app.route("/")
def hello():
    r = requests.get("http://127.0.0.1:5000/api")
    return "I am /" # This never happens :(

@app.route("/api")
def api():
    return "I am /api"

if __name__ == "__main__":
    app.run()

So my questions are: Why does this happen and how can I fix this?

2
  • You actually should just call api to get a result. Not use requests on your own application. Commented Apr 5, 2014 at 10:01
  • @MarkusUnterwaditzer very true in this instance but the usage might occur in a lower layer module like in my case where the function is not invokable. Commented Jun 7, 2017 at 19:40

1 Answer 1

11

You are running your WSGI app with the Flask test server, which by default uses a single thread to handle requests. So when your one request thread tries to call back into the same server, it is still busy trying to handle that one request.

You'll need to enable threading:

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

or use a more advanced WSGI server; see Deployment Options.

Sign up to request clarification or add additional context in comments.

4 Comments

I was not aware of this (until now). Thanks!
From the Flask.run() source it looks like threaded is a kwargs options that ultimately works its way down to werkzeug.serving.run_simple(), which further pushes down to make_server() which then return ThreadedWSGIServer. Is there a way to trigger this for a Flask app instance apart from its run method? I'm trying to utilize this option in the context seen here flask_embed.py which nests the Flask app in some tornado objects.
@jxramos: That code uses a different server to serve the WSGI container (holding the Flask app). Replace that with a threaded server.
I might be constrained by a Tornado server due to the Bokeh setup I'm trying to support. See the linked question at right. So far it looks like Tornado is by design single threaded. Looks like I'll need to deepen my understanding of Bokeh's dependency on Tornado.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.