django - 为什么request.POST对象不可变? [英] django - why is the request.POST object immutable?
问题描述
我知道您可以通过复制发布数据
post = request.POST.copy()
但为什么要这样做?当然这只是让事情变得更加简单呢?还是用于某些其他原因也可能导致问题?
这有点神秘,不是它?几个表面上似乎合理的理论在调查中是错误的:
-
所以
/ li>POST
对象不需要实现变异方法?否:POST
对象属于django.http.QueryDict
class ,它实现了一整套突变方法,包括__ setitem __
,__ delitem __
,pop
和清除
。当您调用其中一种突变方法时,通过检查标志来实现不变性。当您调用复制
方法时,您将获得另一个QueryDict
实例,并启用可变标志。
-
为了提高性能?否:当可变标志关闭时,
QueryDict
类不会获得性能优势。 -
可以将
POST
对象用作字典键?否:QueryDict
对象不可哈希。 -
所以
/ code>数据可以懒惰地构建(而不是承诺读取整个响应),如此声明我在代码中没有看到这一点:据我所知,整个响应总是被读取,直接,或通过 multipart
回复 -
保护您免受编程错误的影响?我已经看到这个声明,但我从来没有看到这些错误是什么的好解释,以及不可变性如何保护你免受他们的伤害。
在任何情况下, POST
不总是不可变的:当响应是 multipart
,然后 POST
是可变的。这似乎把kibosh放在你可能会想到的大多数理论上。 (除非这个行为是一个疏忽)。
总而言之, 我可以看到没有明确的理由在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屋!