如何在after_request函数中更改flask中的响应? [英] How do I alter a response in flask in the after_request function?

查看:101
本文介绍了如何在after_request函数中更改flask中的响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Flask和python的新手.我有一堆视图以jsonify()格式返回字典.对于每个视图,我想添加一个after_request处理函数以更改响应,以便可以向该字典添加键.我有:

I am new to Flask and python. I have a bunch of views that return a dictionary in jsonify() format. For each of these views I'd like to add an after_request handler to alter the response so I can add a key to that dictionary. I have:

@app.route('/view1/')
def view1():
  ..
  return jsonify({'message':'You got served!'})

@app.after_request
def after(response):
  d = json.loads(response.response)
  d['altered'] = 'this has been altered...GOOD!'
  response.response = jsonify(d)
  return response

我得到的错误是"TypeError:列表索引必须是整数,而不是str".请求完成后,如何更改响应字典并添加密钥?

The error I get is "TypeError: list indices must be integers, not str". How do I alter the response dictionary and add a key after the request is completed?

推荐答案

response是WSGI对象,这意味着响应的主体必须是可迭代的.对于jsonify()响应,它只是一个列表,其中只有一个字符串.

response is a WSGI object, and that means the body of the response must be an iterable. For jsonify() responses that's just a list with just one string in it.

但是,您应该在此处使用 response.get_data()方法来检索响应主体,因为这将使您可以迭代的响应变得平坦.

However, you should use the response.get_data() method here to retrieve the response body, as that'll flatten the response iterable for you.

以下应能工作:

d = json.loads(response.get_data())
d['altered'] = 'this has been altered...GOOD!'
response.set_data(json.dumps(d))

不要在这里再次使用jsonify();返回一个完整的新响应对象;您想要的只是这里的JSON响应正文.

Don't use jsonify() again here; that returns a full new response object; all you want is the JSON response body here.

使用 response.set_data() 还将调整Content-Length标头以反映更改后的响应大小.

Do use response.set_data() as that'll also adjust the Content-Length header to reflect the altered response size.

这篇关于如何在after_request函数中更改flask中的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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