request.POST.get('sth')vs request.POST ['sth'] - 区别? [英] request.POST.get('sth') vs request.POST['sth'] - difference?
问题描述
request.POST.get('sth')
和
request.POST [ 'sth']
没有找到类似的问题,两者对我来说都是一样的,假设我可以单独使用它们,但也许我错了,这就是为什么我问。任何想法?
request.POST ['sth']
will如果'sth'
不在 request.POST $ c中,则提出
KeyError
$ c>。
request.POST.get('sth')
将返回没有
如果'sth'
不在 request.POST
。
此外, .get
允许您提供默认值的附加参数,如果该键不在字典中,则返回该参数。例如, request.POST.get('sth','mydefaultvalue')
这是任何python字典,并不是特定于 request.POST
。
这两个片段在功能上是一样的:
第一个片段:
try:
x = request.POST ['sth']
除了KeyError:
x =无
第二个片段: / p>
x = request.POST.get('sth')
这两个片段在功能上是一样的:
第一个片段:
try :
x = request.POST ['sth']
除了KeyError:
x = -1
第二个片段:
x = request.POST.get(ST h',-1)
这两个片段在功能上是相同的:
第一个片段:
如果请求中有'sth'.POST:
x = request.POST ['sth']
else:
x = -1
第二个片段:
x = request.POST.get('sth',-1)
What is the difference between
request.POST.get('sth')
and
request.POST['sth']
Did not find the similar question, both work the same for me, suppose I can use them separately but maybe I am wrong, that is why I am asking. Any ideas?
request.POST['sth']
will raise a KeyError
exception if 'sth'
is not in request.POST
.
request.POST.get('sth')
will return None
if 'sth'
is not in request.POST
.
Additionally, .get
allows you to provide an additional parameter of a default value which is returned if the key is not in the dictionary. For example, request.POST.get('sth', 'mydefaultvalue')
This is the behavior of any python dictionary and is not specific to request.POST
.
These two snippets are functionally identical:
First snippet:
try:
x = request.POST['sth']
except KeyError:
x = None
Second snippet:
x = request.POST.get('sth')
These two snippets are functionally identical:
First snippet:
try:
x = request.POST['sth']
except KeyError:
x = -1
Second snippet:
x = request.POST.get('sth', -1)
These two snippets are functionally identical:
First snippet:
if 'sth' in request.POST:
x = request.POST['sth']
else:
x = -1
Second snippet:
x = request.POST.get('sth', -1)
这篇关于request.POST.get('sth')vs request.POST ['sth'] - 区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!