溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

解決Django的request.POST獲取不到內(nèi)容的問題

發(fā)布時間:2020-08-29 10:47:14 來源:腳本之家 閱讀:240 作者:NoneSec 欄目:開發(fā)技術(shù)

我通過如下的一段程序發(fā)送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)

服務(wù)器端我用request.POST期望能獲取到<QueryDict: {u'key2': [u'value2'], u'key1': [u'value1']}>,但是我發(fā)現(xiàn)獲取到的是一個空的<QueryDict: {}>,用reqyest.body是能獲取到原始的請求內(nèi)容key2=value2&key1=value1的。

這個時候只能去文檔中找答案了,但是貌似Django中的文檔也沒給出我答案,這時候我就只能通過源碼來找答案了,下面是class HttpRequest(object)中獲取POST QueryDict的函數(shù)部分:

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ù)看起來有點長,但是我們只要關(guān)注后面的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'沒有做任何處理,跟我預(yù)想的有一點不一樣。

以上這篇解決Django的request.POST獲取不到內(nèi)容的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI