国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

解決Django的request.POST獲取不到內容的問題

2020-02-15 21:31:48
字體:
來源:轉載
供稿:網友

我通過如下的一段程序發送post請求:

import urllib3pool = 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'沒有做任何處理,跟我預想的有一點不一樣。

以上這篇解決Django的request.POST獲取不到內容的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 乌鲁木齐县| 青岛市| 滁州市| 南安市| 资源县| 洞口县| 公安县| 渭南市| 大埔县| 读书| 福建省| 平果县| 门源| 右玉县| 汝城县| 佛冈县| 攀枝花市| 金秀| 三台县| 明溪县| 砚山县| 木兰县| 红原县| 扶余县| 静宁县| 建始县| 民和| 大庆市| 新乡县| 福泉市| 白银市| 西乌珠穆沁旗| 外汇| 西青区| 灵石县| 正安县| 泸定县| 大丰市| 马边| 沈阳市| 宾川县|