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
432 views
in Technique[技术] by (71.8m points)

python - Requests not able call multiple routes in same Flask application

I am not able to successfully use Python Requests to call a second route in the same application using Flask. I know that its best practice to call the function directly, but I need it to call using the URL using requests. For example:

from flask import Flask
import requests
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"  # This works

@app.route("/myrequest")
def myrequest():
    #r = requests.get('http://www.stackoverflow.com', timeout=5).text  # This works, but is external
    #r = hello()  # This works, but need requests to work
    r = requests.get('http://127.0.0.1:5000/', timeout=5).text  # This does NOT work - requests.exceptions.Timeout
    return r

if __name__ == "__main__":
    app.run(debug=True, port=5000)
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Your code assumes that your app can handle multiple requests at once: the initial request, plus the request that is generated while the initial is being handled.

If you are running the development server like app.run(), it runs in a single thread by default; therefore, it can only handle one request at a time.

Use app.run(threaded=True) to enable multiple threads in the development server.


As of Flask 1.0 the development server is threaded by default.


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

...