如何在Django中request.method == None

mik*_*725 1 python django httprequest

我试图从https://github.com/miki725/Django-jQuery-File-Uploader-Integration-demo/issues/1找出与Django有关的这个问题

request.method == NoneDjango 在什么条件下可以?

Chr*_*gan 6

TL; DR: request.method从来没有None实际使用,但对于你的特殊情况,你看错了.

通用 HttpRequest

django/http/__init__.py:

class HttpRequest(object):
    ...
    def __init__(self):
        ...
        self.method = None
        ...
Run Code Online (Sandbox Code Playgroud)

当一个普通HttpRequest实例化时,它的方法是None.但随后,WSGIRequest并且ModPythonRequest不叫HttpRequest.__init__永远.

请求通过 mod_wsgi

django/core/handlers/wsgi.py:

class WSGIRequest(http.HttpRequest):
    ...
    def __init__(self, environ):
        ...
        self.method = environ['REQUEST_METHOD'].upper()
        ...
Run Code Online (Sandbox Code Playgroud)

这样做的总结是,对于mod_wsgi的,request.method永远None.如果以某种扭曲的方式设置environ['REQUEST_METHOD']为未定义或存在None,请求将失败.

请求通过 mod_python

django/core/handlers/modpython.py:

class ModPythonRequest(http.HttpRequest):
    ...
    def _get_method(self):
        return self.META['REQUEST_METHOD'].upper()
    ...
    method = property(_get_method)
Run Code Online (Sandbox Code Playgroud)

WSGIRequest申请相同的评论.不可能None.

测试客户端

django.test.client.RequestFactory.request实例化a WSGIRequest并且每次都被调用REQUEST_METHOD,并且environ作为大写字符串定义,应该如此.


摘要:

assert request.method is not None
Run Code Online (Sandbox Code Playgroud)

你在错误的地方寻找错误.在这种情况下,request.method == 'POST'.它失败了request.META.get('CONTENT_TYPE', '') is None.原因是Content-Type客户端在请求中没有发送标头(不要问我为什么,我不熟悉那些东西).