Home > flask > Flask: cannot fetch a URL on localhost

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.

What happened?
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 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__)

def hello_world():
    return "Hello, World!"

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__":
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: