request.POST与request.POST.get两者的不同之处(Django学习)

request.POST是用来接受从前端表单中传过来的数据,比如用户登录过程中传递过来的username、passwrod等字段。

我们在后台进行数据获取时,有两种方法(以username为例):request.POST[‘username’]与request.POST.get(‘username’),那么这两者有什么不同之处呢?

如果传递过来的数值不为空,那么这两种方法都没有错误,可以得到相同的结果。但是如果传递过来的数值为空,那么request.POST[‘username’]则会提示Keyerror错误,而request.POST.get(‘username’)则不会报错,而是返回一个none。

下面来自大佬的解释:

request.POST.get('sth') vs request.POST['sth'] - difference?

答:

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')
snippets
n. 片段(snippet的复数形式);小片

functionally
adv. 功能地;函数地;职务上地

identical
n. 完全相同的事物adj. 同一的;完全相同的

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)

猜你喜欢

转载自blog.csdn.net/lezeqe/article/details/87936597
今日推荐