从 Flask 返回一个 requests.Response 对象 [英] Return a requests.Response object from Flask
问题描述
我正在尝试使用 Flask 和请求构建一个简单的代理.代码如下:
I'm trying to build a simple proxy using Flask and requests. The code is as follows:
@app.route('/es/<string:index>/<string:type>/<string:id>',
methods=['GET', 'POST', 'PUT']):
def es(index, type, id):
elasticsearch = find_out_where_elasticsearch_lives()
# also handle some authentication
url = '%s%s%s%s' % (elasticsearch, index, type, id)
esreq = requests.Request(method=request.method, url=url,
headers=request.headers, data=request.data)
resp = requests.Session().send(esreq.prepare())
return resp.text
这有效,只是它丢失了来自 Elasticsearch 的状态代码.我尝试直接返回 resp
(a requests.models.Response
),但这失败了
This works, except that it loses the status code from Elasticsearch. I tried returning resp
(a requests.models.Response
) directly, but this fails with
TypeError: 'Response' object is not callable
是否有另一种简单的方法可以从 Flask 返回 requests.models.Response
?
Is there another, simple, way to return a requests.models.Response
from Flask?
推荐答案
好的,找到了:
如果返回一个元组,元组中的项目可以提供额外的信息.此类元组必须采用(响应、状态、标题)形式.状态值将覆盖状态代码,标题可以是附加标题值的列表或字典.
If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form (response, status, headers). The status value will override the status code and headers can be a list or dictionary of additional header values.
(Flask 文档.)
所以
return (resp.text, resp.status_code, resp.headers.items())
似乎可以解决问题.
这篇关于从 Flask 返回一个 requests.Response 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!