在我的烧瓶应用程序上,我有一条路线(http://localhost:5000/api/users/),它从数据库中以 JSON 格式返回用户列表,并且在通过 curl 或谷歌浏览器邮递员请求时它工作得很好。假设路线是声明为以下代码:
@app.route('/api/users/')
def users():
return 'Some json results...'
但是,在我的应用程序中,有一点我需要使用相同的用户列表,因此我决定提交一个get请求,并从“ / api / users /”路由中提取用户。我已经安装了 python requests 库,这里是下面的路由定义,它应该返回相同的用户列表:
@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"
}
我尝试了许多外部网址,并且每个网址都没有任何问题地通过,它只是在向自己的路由/网址提交请求时停止工作。
这个场景只是为了理解,我需要实现一些更复杂的东西,这就是为什么我必须向应用程序自己的路由提交请求。不知道出了什么问题,坚持了这么久。很感谢任何形式的帮助。
更新:启用线程,它开始工作正常,要求关闭这个问题。
解决方法:在烧瓶路由功能中使用请求模块
发生这种情况是因为您的 Flask 服务器只有一个线程。当您发出请求时,线程会处理您的请求,并且无法处理它在处理过程中所做的另一个请求。
尝试使用不同的端口运行另一个进程并更改您的网址,它会起作用。此外,您可以使用--with-threads
选项运行您的服务器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句