Resolved an issue where Django's ES1en.POST could not get content

  • 2020-10-07 18:45:58
  • OfStack

I send the post request through the following 1 program:


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)

On the server side I use request.POST and expect to get it < QueryDict: {u'key2': [u'value2'], u'key1': [u'value1']} > , but I found that I got 1 empty < QueryDict: {} > , reqyest. body is to get the original request content key2=value2 & key1 = value1.

At this time, I can only find the answer in the document, but it seems that the document in Django does not give me the answer, at this time, I can only find the answer through the source code, the following is the function part of class HttpRequest(object) to get 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()

The function looks a bit long, but we only need to focus on the following three branches of if elif else, from elif self.content_type == 'application/ x-ES40en-ES41en-ES42en ': this branch can see that only 'Content-ES45en' in request header: 'application/ ES47en-ES48en-ES49en-ES50en 'fills request.POST, otherwise only 1 is empty < QueryDict: {} > .

It can also be seen from this problem that Django did not do any processing on 'Content-ES60en ':'application/json', which is one point different from what I expected.


Related articles: