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

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

问题描述

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

  from flask import Flask 
import requests
app = Flask(__ name__)

@ app.route(/)
def hello():
返回Hello World! #这工程

@ app.route(/ myrequest)
def myrequest():
#r = requests.get('http://www.stackoverflow。 com',timeout = 5).text#这个工作,但是是外部
#r = hello()#这个工作,但需要请求工作
r = requests.get('http://127.0 .0.1:5000 /',timeout = 5).text#这是行不通的 - requests.exceptions.Timeout
return r

if __name__ ==__main__:
app.run(debug = True,port = 5000)


解决方案

您的代码假定您的应用程序可以同时处理多个请求:初始请求,以及在处理初始请求时生成的请求。



如果您正在运行像 app.run()这样的开发服务器,它默认运行在一个单独的线程中。因此,它一次只能处理一个请求。
$ b

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


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.

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.

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

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