在瓶颈路由功能中使用请求模块 [英] Using requests module in flask route function

查看:132
本文介绍了在瓶颈路由功能中使用请求模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的最小工作烧瓶应用程序:

  from flask import Flask 

app = Flask (__name__)

@ app.route(/)
def hello():
返回我是/

@app。 route(/ api)
def api():
返回我是/ api

if __name__ ==__main__:
app.run ()

这很愉快地工作。但是,当我尝试使用请求模块从 hello 路由到 api 路由的GET请求时,当试图访问 http://127.0.0.1:5000/



<$ p时,我从来没有在浏览器中得到响应$ p $ from flask import Flask
import requests
$ b $ app = Flask(__ name__)

@ app.route(/)
def hello():
r = requests.get(http://127.0.0.1:5000/api)
return我是/#这从来不会发生:(

@ app.route(/ api)
def api():
returnI am / api

if __name__ ==__main__ :
app.run()

所以我的问题是:为什么会发生这种情况,我怎样才能解决这个问题?

解决方案

您正在使用Flask测试服务器运行WSGI应用程序,默认情况下使用单个线程来处理请求,所以当你的一个请求线程试图回调到同一个服务器时,它仍然忙于处理这个o



$ b

您需要启用线程:

  if __name__ ==__main__:
app.run(threaded = True)



或者使用更高级的WSGI服务器;请参阅部署选项


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?

解决方案

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.

这篇关于在瓶颈路由功能中使用请求模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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