Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

python - Using requests module in flask route function

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...