我想這個問題涉及到的Django從https://github.com/miki725/Django-jQuery-File-Uploader-Integration-demo/issues/1如何request.method ==沒有在Django
在Django搞清楚在什麼條件下可以request.method == None
?
我想這個問題涉及到的Django從https://github.com/miki725/Django-jQuery-File-Uploader-Integration-demo/issues/1如何request.method ==沒有在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
,被稱爲與REQUEST_METHOD
每次在environ
定義爲大寫的字符串,因爲它應該是。
摘要:
assert request.method is not None
你在找錯了地方的錯誤。在這種情況下,request.method == 'POST'
。當request.META.get('CONTENT_TYPE', '') is None
失敗。原因是Content-Type
標題不是由客戶端在請求中發送(不要問我爲什麼,我不熟悉那些東西)。
我能得到這個通過AJAX的發生,特別呼籲jQuery的$就功能(見http://api.jquery.com/jQuery.ajax/)用「POST」類型,但沒有數據:
$.ajax({
type: "POST",
url: "/something",
});
旁白:請記住,當你檢查'None'使用'is'而不是'==',因爲它更具體。 –
謝謝。我總是忘記這麼做...... – miki725