1. 程式人生 > >Django的request.POST獲取不到內容的原因

Django的request.POST獲取不到內容的原因

我通過如下的一段程式傳送post請求:

import urllib3
pool = urllib3.connection_from_url('http://127.0.0.1:8090')
resp = pool.request('POST', '/polls/', fields={'key1':'value1', 'key2':'value2'}, headers={'Content-Type':'application/json'}, encode_multipart=False)

在伺服器端我用request.POST期望能獲取到<QueryDict: {u'key2': [u'value2'], u'key1': [u'value1']}>

,但是我發現獲取到的是一個空的<QueryDict: {}>,用reqyest.body是能獲取到原始的請求內容key2=value2&key1=value1的。
這個時候只能去文件中找答案了,但是貌似Django中的文件也沒給出我答案,這時候我就只能通過原始碼來找答案了,下面是class HttpRequest(object)中獲取POST QueryDict的函式部分:

    def _load_post_and_files(self):
        """Populate self._post and self._files if the content-type is a form type"""
if self.method != 'POST': self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict() return if self._read_started and not hasattr(self, '_body'): self._mark_post_parse_error() return if self.content_type == 'multipart/form-data'
: if hasattr(self, '_body'): # Use already read data data = BytesIO(self._body) else: data = self try: self._post, self._files = self.parse_file_upload(self.META, data) except MultiPartParserError: # An error occurred while parsing POST data. Since when # formatting the error the request handler might access # self.POST, set self._post and self._file to prevent # attempts to parse POST data again. # Mark that an error occurred. This allows self.__repr__ to # be explicit about it instead of simply representing an # empty POST self._mark_post_parse_error() raise elif self.content_type == 'application/x-www-form-urlencoded': self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict() else: self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()

函式看起來有點長,但是我們只要關注後面的if elif else這三個分支即可,從elif self.content_type == 'application/x-www-form-urlencoded':這個分支能看到只有請求header中的'Content-Type':'application/x-www-form-urlencoded'才會填充request.POST,其它情況下只有一個空的<QueryDict: {}>
從這個問題也看到了Django對'Content-Type':'application/json'沒有做任何處理,跟我預想的有一點不一樣。