【问题标题】:Python Requests library not working with Flask app own routesPython Requests 库不适用于 Flask 应用程序自己的路由
【发布时间】:2017-08-02 19:03:17
【问题描述】:

在我的烧瓶应用程序中,我有一个路由 (http://localhost:5000/api/users/),它以 JSON 格式从数据库返回用户列表,并且在通过 curl 或 google chrome postman 请求时它工作得非常好。假设路由声明为以下代码:

@app.route('/api/users/')
def users():
    return 'Some json results...'

但是,在我的应用程序中,我有另一条路线需要使用相同的用户列表,因此我决定提交一个获取请求并从“/api/users/”路线中拉出用户。我已经安装了 python 请求库,下面是应该返回相同用户列表的路由定义:

@app.route('/api/someroute/')
def someroute():
    r = requests.get('http://localhost:5000/api/users/')
    return r.json()

现在通过邮递员或 curl 向这条路线('/api/someroute/')提交一个获取请求,直到我关闭应用程序之前一直加载。它什么也不返回,没有错误,还冻结所有其他路线。就像当我尝试从用户路由('/api/users/')请求数据时,请求仍在加载“someroute”时也会继续加载。但是当我尝试从一些外部 url 请求数据时,它工作正常。下面是自定义的外部资源请求数据代码:

@app.route('/api/someroute/')
def someroute():
    r = requests.get('https://jsonplaceholder.typicode.com/posts/1')
    return r.json()

现在向 someroute 提交 get 请求可以正常工作并按预期返回数据

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

我尝试了许多外部网址,每个网址都通过了,没有任何问题,当向它自己的路由/网址提交请求时它就停止工作了。

这个场景只是为了理解,我需要实现更复杂的东西,这就是为什么我必须向应用程序自己的路由提交请求。不知道出了什么问题,卡了这么久。非常感谢任何帮助。

更新:启用线程并开始正常工作,请求关闭此问题。
解决者:Using requests module in flask route function

【问题讨论】:

    标签: python curl flask routing python-requests


    【解决方案1】:

    这是因为你的烧瓶服务器有一个线程。当您请求时,线程会处理您的请求,并且无法处理它在处理期间执行的另一个请求。

    尝试使用不同的端口运行另一个进程并更改您的 url,它会起作用。此外,您可以使用--with-threads 选项运行您的服务器。

    【讨论】:

    • 非常感谢您的回答。启用多线程让一切正常。
    • 抱歉不小心点击了。再次标记为正确的解决方案:) 谢谢
    猜你喜欢
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 2020-06-07
    • 2018-11-01
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 2011-01-28
    相关资源
    最近更新 更多