修改django请求中body的值

Modify value of body in django request

我想在我的 django API 的 post 请求 中更新 json 主体值的值(也使用 rest框架),现在我正在尝试使用自定义中间件来做到这一点。这是我的中间件。

def CustomMiddleware(get_response):
    def middleware(request):

        print('request: ', request, ' type: ', type(request), ' vars: ', vars(request))
        print('request: ', request.body)
        body = json.loads(request.body)
        body['attr'] = str(body['attr'])+'abc'
        request.body = json.dumps(body)
        response = get_response(request)
        return response

return middleware

因此,当我向我的 API 发出 POST 请求时,我得到了这个错误:

File "/path/models_masking/mask_middleware.py", line 37, in middleware
    request.body = json.dumps(request_updated)
AttributeError: can't set attribute

我阅读并发现 request 对象是不可变的,所以我不确定我是否能够复制到请求对象,修改副本然后将其发送到 get_response 函数,或者也许有更好的方法来做到这一点,也许是我的 APIView 类.

的装饰器

谁能帮我解决这个问题?

编辑

'attr'+'abc' 的值是在代码库的很多部分中使用的新值,我的核心问题是我不想在许多请求端点中有很多功能,所以我的第一个想法是更新请求的值以在所有请求中自动更改 'attr' 的值,而不是更新每个请求。

这可能是一个新问题,但如果有人能为我的问题提供更好的解决方案,我将不胜感激。

我同意其他人的看法,更改请求的主体并不常见,但如果您确实需要,那么您可以设置 request._body,因为 body 只是一个 属性

    @property
    def body(self):
        if not hasattr(self, '_body'):
            if self._read_started:
                raise RawPostDataException("You cannot access body after reading from request's data stream")

            # Limit the maximum request data size that will be handled in-memory.
            if (settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and
                    int(self.META.get('CONTENT_LENGTH') or 0) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE):
                raise RequestDataTooBig('Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.')

            try:
                self._body = self.read()
            except IOError as e:
                raise UnreadablePostError(*e.args) from e
            self._stream = BytesIO(self._body)
        return self._body

仅接受的答案对我来说意义不大。但我还发现 是基于已接受的答案本身。附加的 Whosebug 为所有者的问题提供了更具描述性的答案,还为在请求中设置正文时可能发生的问题提供了解决方案。