Skip to main content
 首页 » 编程设计

python之如何在 Django 中 request.method == None

2025年05月04日36powertoolsteam

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

Django 中request.method == None 什么情况下可以?

请您参考如下方法:

TL;DR: request.method 在实际使用中永远不会是 None,但对于您的特定情况,您正在查看错误的事情。

通用HttpRequest

django/http/__init__.py:

class HttpRequest(object): 
    ... 
    def __init__(self): 
        ... 
        self.method = None 
        ... 

当一个普通的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() 
        ... 

总结一下,对于 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) 

与 WSGIRequest 相同的注释适用。永远不能是 None。

测试客户端

django.test.client.RequestFactory.request 实例化一个 WSGIRequest 并且每次使用 environ 中定义的 REQUEST_METHOD 调用 作为大写字符串,这是应该的。


总结:

assert request.method is not None 

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