Flask: cannot fetch a URL on localhost
I had a simple Flask application that included a web service, i.e. calling an address returns some value (a JSON result for instance). I wanted to reuse this service inside the app. by simply calling it (via the HTTP protocol) and getting the return value. However, this call never finished. The browser was loading and I got no result.
I posted the problem here and it turned out that “the development server is single threaded, so when you call a url served by that application from within the application itself, you create a deadlock situation.” Hmm…
My first idea was to replace the dev. server with a more serious one. With gunicorn I could make it work:
gunicorn -w 4 -b 127.0.0.1:5000 hello:app
However, I deploy the app. on Heroku, where you have just 1 worker for free, so it behaves just like the dev. server!
I had to rewrite the code to eliminate this extra call. (Or, I could have kept this call if I had had at least 2 worker threads.)
Here is a simplified code that demonstrates the problem:
#!/usr/bin/env python # hello.py from flask import Flask from flask import url_for import requests app = Flask(__name__) @app.route('/') def hello_world(): return "Hello, World!" @app.route('/get') def get(): url = url_for("hello_world", _external=True) # full URL print '!!!', url # debug info r = requests.get(url) # it hangs at this point return "from get: " + r.text if __name__ == "__main__": app.run(debug=True)