我通過如下的一段程序發(fā)送post請求:
在服務(wù)器端我用request.POST期望能獲取到<QueryDict: {u'key2': [u'value2'], u'key1': [u'value1']}>,但是我發(fā)現(xiàn)獲取到的是一個(gè)空的<QueryDict: {}>,用reqyest.body是能獲取到原始的請求內(nèi)容key2=value2&key1=value1的。
這個(gè)時(shí)候只能去文檔中找答案了,但是貌似Django中的文檔也沒給出我答案,這時(shí)候我就只能通過源碼來找答案了,下面是class HttpRequest(object)中獲取POST QueryDict的函數(shù)部分:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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() |
函數(shù)看起來有點(diǎn)長,但是我們只要關(guān)注后面的if elif else這三個(gè)分支即可,從elif self.content_type == 'application/x-www-form-urlencoded':這個(gè)分支能看到只有請求header中的'Content-Type':'application/x-www-form-urlencoded'才會填充request.POST,其它情況下只有一個(gè)空的<QueryDict: {}>。
從這個(gè)問題也看到了Django對'Content-Type':'application/json'沒有做任何處理,跟我預(yù)想的有一點(diǎn)不一樣。
以上這篇解決Django的request.POST獲取不到內(nèi)容的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/liuxingen/article/details/54176205