代码之家  ›  专栏  ›  技术社区  ›  Art

检查Django中的请求类型

  •  8
  • Art  · 技术社区  · 16 年前

    虽然建议使用以下构造来检查请求是否为POST,

    if request.method == 'POST':
        pass
    

    if request.POST:
        pass
    

    除了个人喜好之外,还有什么理由不使用它吗?

    1 回复  |  直到 16 年前
        1
  •  21
  •   miku    16 年前

    文件对此很清楚:

    一个请求可能是通过带有空POST字典的POST传入的——例如,如果一个表单是通过posthttp方法请求的,但不包括表单数据。因此,您不应该使用if request.POST来检查POST方法的使用;相反,使用if request.method==“POST”(见上文)。

    >>> # 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