Python请求库不使用Flask应用程序自己的路由

2024-09-30 08:31:46 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的flask应用程序中,我有一个route(http://localhost:5000/api/users/),它以JSON格式从数据库返回用户列表,当通过curl或googlechrome请求时,它工作得非常好邮递员。假设路线声明如下:

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

不过,在我的应用程序中,我有另一个需要使用相同用户列表的路由,因此我决定提交一个get请求,并从“/api/users/”路由中提取用户。用户在这里返回的python路径和我应该安装的库的定义相同:

^{pr2}$

现在通过postman或curl向这个路由('/api/someroute/')提交一个get请求,直到我关闭应用程序为止。它什么也不返回,没有错误,也冻结了所有其他路由。就像当我试图从用户那里请求数据时,如果我仍在为“someroute”加载请求,route('/api/users/')也会继续加载。但当我试图从外部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"
}

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

这个场景只是为了理解,我需要实现更复杂的东西,这就是为什么我必须向appown提交请求路线。有不知道出了什么问题,坚持了这么久。非常感谢任何帮助。在

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


Tags: 数据用户apiapp应用程序flask路由列表
1条回答
网友
1楼 · 发布于 2024-09-30 08:31:46

这是因为你的flask服务器只有一个线程。当您请求时,线程处理您的请求,并且不能处理它在处理期间执行的另一个请求。在

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

相关问题 更多 >

    热门问题