国产探花免费观看_亚洲丰满少妇自慰呻吟_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獲取不到內容的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 金堂县| 南靖县| 吉首市| 金川县| 城市| 车险| 庆云县| 开封市| 安国市| 上饶县| 宾川县| 阿城市| 湘潭市| 秭归县| 清丰县| 会理县| 东平县| 商河县| 武清区| 电白县| 全南县| 汾西县| 仁化县| 二手房| 石狮市| 白银市| 黔江区| 鄯善县| 丰镇市| 抚松县| 兰考县| 南召县| 鱼台县| 黎川县| 星座| 沙洋县| 八宿县| 黄浦区| 枣庄市| 临湘市| 湄潭县|