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

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

问题描述

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

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()

这很有效.但是,当我尝试使用从 hello 路由到 api 路由的请求"模块发出 GET 请求时 - 我在尝试访问时从未在浏览器中收到响应http://127.0.0.1:5000/

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?

推荐答案

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

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.

您需要启用线程:

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

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

or use a more advanced WSGI server; see Deployment Options.

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

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