[英]How can request.method == None in Django
I am trying to figure out this issue related to Django from https://github.com/miki725/Django-jQuery-File-Uploader-Integration-demo/issues/1 我正在尝试从https://github.com/miki725/Django-jQuery-File-Uploader-Integration-demo/issues/1找出与Django相关的问题
Under what conditions can request.method == None
in Django? 在什么情况下
request.method == None
在Django中request.method == None
?
TL;DR: request.method
is never None
in real use, but for your particular case, you're looking at the wrong thing. TL; DR:
request.method
在实际使用中永远None
是None
,但是对于您的特定情况,您正在寻找错误的东西。
HttpRequest
HttpRequest
django/http/__init__.py
: django/http/__init__.py
:
class HttpRequest(object):
...
def __init__(self):
...
self.method = None
...
When a plain HttpRequest
is instantiated, its method is None
. 实例化纯
HttpRequest
,其方法为None
。 But then, WSGIRequest
and ModPythonRequest
don't call HttpRequest.__init__
ever. 但是,然后
WSGIRequest
和ModPythonRequest
不会调用HttpRequest.__init__
。
mod_wsgi
mod_wsgi
请求 django/core/handlers/wsgi.py
: django/core/handlers/wsgi.py
:
class WSGIRequest(http.HttpRequest):
...
def __init__(self, environ):
...
self.method = environ['REQUEST_METHOD'].upper()
...
The summary of this is that for mod_wsgi, request.method
will never be None
. 对此的总结是,对于mod_wsgi,
request.method
永远不会为None
。 If in some warped way you managed to get environ['REQUEST_METHOD']
not being defined or being None
, the request would fail. 如果以某种扭曲的方式设法使
environ['REQUEST_METHOD']
未定义或为None
,则请求将失败。
mod_python
mod_python
请求 django/core/handlers/modpython.py
: django/core/handlers/modpython.py
:
class ModPythonRequest(http.HttpRequest):
...
def _get_method(self):
return self.META['REQUEST_METHOD'].upper()
...
method = property(_get_method)
Same remarks as with WSGIRequest
apply. 与
WSGIRequest
注释相同。 Can't ever be None
. 永远不能
None
。
django.test.client.RequestFactory.request
instantiates a WSGIRequest
and is called every time with REQUEST_METHOD
defined in the environ
as an uppercase string, as it should be. django.test.client.RequestFactory.request
实例化一个WSGIRequest
并且每次都使用environ
定义为大写字符串的REQUEST_METHOD
调用。
Summary: 摘要:
assert request.method is not None
You're looking for the error in the wrong place. 您在错误的位置寻找错误。 In this case,
request.method == 'POST'
. 在这种情况下,
request.method == 'POST'
。 It's failing when request.META.get('CONTENT_TYPE', '') is None
. request.META.get('CONTENT_TYPE', '') is None
时失败。 The reason for this is that the Content-Type
header isn't being sent by the client in the request (don't ask me why, I'm not familiar with that stuff). 原因是客户端没有在请求中发送
Content-Type
标头(不要问我为什么,我对那些东西不熟悉)。
I was able to get this to happen via AJAX, specifically calling jQuery's $.ajax function (see http://api.jquery.com/jQuery.ajax/ ) with "POST" type but no data: 我能够通过AJAX做到这一点,特别是使用“ POST”类型但没有数据调用jQuery的$ .ajax函数(请参阅http://api.jquery.com/jQuery.ajax/ ):
$.ajax({
type: "POST",
url: "/something",
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.