我使用 Python 中的 Bottle 库创建了一个 API。它的端点看起来像这样
@app.get('/api/users/<id>', name='user')
def get_user(model, id):
user = model.get_user(id)
if not user:
return HTTPError(404, 'User not found')
else:
response.content_type = "application/json"
return json.dumps(user)
我想在同一个应用的其他函数中调用API
@app.route('/users/<id>')
def users (id=1):
user = request.get("http://localhost:8001/api/user/1")
return template('user', user=user)
但是,这没有显示任何结果。请求每次都超时
所以我的问题是,如何使用 Requests 库或通过任何其他方式从该应用程序中调用 Bottle API。
最佳答案
您是否以单线程模式(默认)运行 Bottle?如果是这样,那么你的内部 get
请求将永远挂起。这是因为您的服务器一次只能处理一个请求,而您要求它同时处理两个请求:第一次调用 /users/<id>
。 , 然后第二次调用 /api/users/<id>
.
创可贴解决方案是 run the server in asynchronous mode .试试这个方法,看看你的超时是否消失:
run(host='0.0.0.0', port=YOUR_PORT_NUMBER, server='gevent')
但是:您一开始就不应该以这种方式设计您的应用程序。相反,请重构您的代码,以便两种方法都可以调用返回用户 JSON 表示形式的函数。然后一个 api 调用可以返回原始 json 对象,而另一个 api 调用可以将其呈现为 HTML。注意:这不是我设计此 API 的方式,但它是与您迄今为止构建应用程序的方式最短距离的答案。
关于python - 如何从该应用程序中调用 Python Bottle API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61836265/