2011-10-20 24 views

回答

6

TL; DR:request.method從來沒有None在實際使用,但對於您的具體情況,你看錯了東西。

通用HttpRequest

django/http/__init__.py

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

當一個普通HttpRequest被實例化,其方法是None。但是,WSGIRequestModPythonRequest不會呼叫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標題不是由客戶端在請求中發送(不要問我爲什麼,我不熟悉那些東西)。

0

我能得到這個通過AJAX的發生,特別呼籲jQuery的$就功能(見http://api.jquery.com/jQuery.ajax/)用「POST」類型,但沒有數據:

$.ajax({ 
     type: "POST", 
     url: "/something", 
    });