从Flask中返回一个requests.Response对象 [英] Return a requests.Response object from Flask

查看:294
本文介绍了从Flask中返回一个requests.Response对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Flask和请求来构建一个简单的代理。代码如下:

  @ app.route('/ es /< string:index> /< string:类型> /< string:id>',
methods = ['GET','POST','PUT']]:
def es(index,type,id):
elasticsearch = find_out_where_elasticsearch_lives()
#也处理一些认证
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 ),但是这个失败,并且带有

  TypeError:'Response'对象不可调用

是否有另外一个简单的方法可以从Flask返回 requests.models.Response


如果元组返回,元组中的元素可以返回提供额外的信息。这样的元组必须以表单(响应,状态,头部)的形式存在,至少有一个元素必须位于元组中。状态值将覆盖状态码,标题可以是附加标题值的列表或字典。


文档



所以

  return(resp.text,resp.status_code,resp.headers.items())

似乎可以做到这一点。


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

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

Is there another, simple, way to return a requests.models.Response from Flask?

解决方案

Ok, found it:

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) where at least one item has to be in the tuple. The status value will override the status code and headers can be a list or dictionary of additional header values.

(Flask docs.)

So

return (resp.text, resp.status_code, resp.headers.items())

seems to do the trick.

这篇关于从Flask中返回一个requests.Response对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆