请求无法在同一个 Flask 应用程序中调用多个路由 [英] Requests not able call multiple routes in same Flask application

查看:25
本文介绍了请求无法在同一个 Flask 应用程序中调用多个路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法成功地使用 Python 请求在使用 Flask 的同一应用程序中调用第二个路由.我知道直接调用函数的最佳做法是,但我需要它使用请求的 URL 进行调用.例如:

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)

推荐答案

您的代码假定您的应用可以一次处理多个请求:初始请求,加上处理初始请求时生成的请求.

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.

如果你像 app.run() 一样运行开发服务器,它默认在单线程中运行;因此,它一次只能处理一个请求.

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.

使用 app.run(threaded=True) 在开发服务器中启用多线程.

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

从 Flask 1.0 开始,开发服务器默认是线程化的.

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

这篇关于请求无法在同一个 Flask 应用程序中调用多个路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆