Check request type in Django
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
精彩评论