开发者

Check request type in Django

开发者 https://www.devze.com 2023-01-01 07:20 出处:网络
While it is recommended to use the following construct to check whether request is POST, if request.method == \'POST\':

While it is recommended to use the following construct to check whether request is POST,

if request.method == 'POST':
    pass

It is likely that people will find

if request开发者_JS百科.POST:
    pass

to be more elegant and concise.

Are there any reasons not to use it, apart from personal preference?


The documentation is clear about this:

  • http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.POST

It's possible that a request can come in via POST with an empty POST dictionary -- if, say, a form is requested via the POST HTTP method but does not include form data. Therefore, you shouldn't use if request.POST to check for use of the POST method; instead, use if request.method == "POST" (see above).

>>> # assume an empty POST request would be treated as a dict
>>> bool({})
False
>>> # it would be a POST request, but request.POST would evaluate to False
0

精彩评论

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