django - 为什么 request.POST 对象是不可变的? [英] django - why is the request.POST object immutable?
问题描述
正如标题所问,为什么 Django 人决定使用 querydict 来实现 request.POST 对象(当然,这反过来又使整个事情不可变?)
我知道你可以通过复制帖子数据来修改它
post = request.POST.copy()
但是为什么要这样做呢?当然,只是允许事物可变会更简单吗?或者它是否也被用于其他可能导致问题的原因?
这有点神秘,不是吗?几个表面上似是而非的理论在调查中被证明是错误的:
这样
POST
对象就不必实现突变方法了吗?否:POST
对象属于django.http.QueryDict
类,实现了包括__setitem__
、__delitem__
、在内的全套变异方法pop
和clear
.它通过在调用其中一种变异方法时检查标志来实现不变性.当你调用copy
方法时,你会得到另一个QueryDict
实例,并打开了可变标志.为了提高性能?否:当可变标志关闭时,
QueryDict
类不会获得性能优势.这样
POST
对象就可以用作字典键了吗?否:QueryDict
对象不可散列.以便可以延迟构建
POST
数据(无需承诺读取整个响应),如此处所述?我在代码中没有看到这方面的证据:据我所知,整个响应总是被读取,要么 直接,或通过MultiPartParser
用于multipart
响应.保护您免受编程错误的影响?我已经看到了这种说法,但我从来没有看到过对这些错误是什么以及不可变性如何保护您免受这些错误的良好解释.
在任何情况下,POST
并不总是不可变的:当响应是 multipart
时,POST
是可变的.这似乎使您可能想到的大多数理论都变得不切实际.(除非这种行为是疏忽.)
总而言之,我在 Django 中看不到 POST
对象对于非 multipart
请求是不可变的明确理由.>
As the title asks, why did the Django guys decide to implement the request.POST object with a querydict (which, of course, in turn, makes the whole thing immutable?)
I know you can mutify it by making a copy of the post data
post = request.POST.copy()
but why do this? Surely it would be simpler just to allow the thing to be mutable anyway? Or is it being used for some other reason too which might cause issue?
It's a bit of a mystery, isn't it? Several superficially plausible theories turn out to be wrong on investigation:
So that the
POST
object doesn't have to implement mutation methods? No: thePOST
object belongs to thedjango.http.QueryDict
class, which implements a full set of mutation methods including__setitem__
,__delitem__
,pop
andclear
. It implements immutability by checking a flag when you call one of the mutation methods. And when you call thecopy
method you get anotherQueryDict
instance with the mutable flag turned on.For performance improvement? No: the
QueryDict
class gains no performance benefit when the mutable flag is turned off.So that the
POST
object can be used as a dictionary key? No:QueryDict
objects are not hashable.So that the
POST
data can be built lazily (without committing to read the whole response), as claimed here? I see no evidence of this in the code: as far as I can tell, the whole of the response is always read, either directly, or viaMultiPartParser
formultipart
responses.To protect you against programming errors? I've seen this claimed, but I've never seen a good explanation of what these errors are, and how immutability protects you against them.
In any case, POST
is not always immutable: when the response is multipart
, then POST
is mutable. This seems to put the kibosh on most theories you might think of. (Unless this behaviour is an oversight.)
In summary, I can see no clear rationale in Django for the POST
object to be immutable for non-multipart
requests.
这篇关于django - 为什么 request.POST 对象是不可变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!