【问题标题】:Updating requests Response content in Python在 Python 中更新请求响应内容
【发布时间】:2021-04-27 10:16:38
【问题描述】:

我是 Python 新手。我正在尝试更改使用请求库在交换响应中获得的 Json 正文。

我想做这样的事情:

import json
import requests

def request_and_fill_form_in_response() -> requests.Response():
    response = requests.get('https://someurl.com')
    body_json = response.json()
    body_json['some_field'] = 'some_value'
    response.content = json.dumps(body_json)
    return response

在这种特殊情况下,我只对更新 response.content 对象感兴趣(不管这是否是一种好的做法)。

这可能吗?

(顺便说一句,上面的代码抛出 'AttributeError: can't set attribute' 错误,这几乎是不言自明的,但我想确保我没有遗漏什么)

【问题讨论】:

    标签: python json python-requests


    【解决方案1】:

    你可以这样重写内容:

    from json import dumps
    from requests import get, Response
    
    
    def request_and_fill_form_in_response() -> Response:
        response = get('https://mocki.io/v1/a9fbda70-f7f3-40bd-971d-c0b066ddae28')
        body_json = response.json()
        body_json['some_field'] = 'some_value'
        response._content = dumps(body_json).encode()
        return response
    
    
    response = request_and_fill_form_in_response()
    
    print(response.json())
    

    结果是: {'name': 'Aryan', 'some_field': 'some_value'}

    但从技术上讲,_content 是一个私有变量,必须有一个方法作为 setter 来为其赋值。 此外,您也可以创建自己的 Response 对象。 (可以查看回复方式here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-12
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-19
      • 2020-08-04
      相关资源
      最近更新 更多