开发者

Django - sometimes request.POST is mutable, sometimes it isn't

开发者 https://www.devze.com 2023-02-08 06:42 出处:网络
I\'m working on some legacy Django code. I have two nearly-identical views: @login_required def foo(request):

I'm working on some legacy Django code. I have two nearly-identical views:

@login_required
def foo(request):
    assert False, "foo mutable=%s" % request.POST._mutable

@login_required
def bar(request):
    assert False, "foo mutable=%s" % request.POST._mutable

Strangely _mutable is True for one of the handlers and False for the other.

There is no custom middleware and the stack traces on the resulting Django debug page are practically the same.

Sure, I can get around the problem by using request.POST.copy() or request.POST._mutable = True to make the/a QueryDict object mutable, but I'开发者_运维知识库d like to know what could be causing this.


By default it should always be False, the only place in the Django code that sets it to True is in the MultiPartParser.parse, which only happens if the CONTENT_TYPE starts with multipart.

From _load_post_and_files in HttpRequest:

if self.META.get('CONTENT_TYPE', '').startswith('multipart'):
    self._raw_post_data = ''
    try:
        self._post, self._files = self.parse_file_upload(self.META, self)
        ...

From parse_file_upload:

parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
return parser.parse()

And from MultiPartParser.parse:

self._post = QueryDict('', mutable=True)
...
return self._post, self._files

So if one view is getting multipart requests and the other is not, that would explain the difference.

0

精彩评论

暂无评论...
验证码 换一张
取 消