{"id":3927,"date":"2018-05-19T15:13:46","date_gmt":"2018-05-19T07:13:46","guid":{"rendered":"https:\/\/ixyzero.com\/blog\/?p=3927"},"modified":"2018-06-02T20:34:23","modified_gmt":"2018-06-02T12:34:23","slug":"django%e4%b8%ad%e7%9a%84request-post%e5%92%8crequest-body","status":"publish","type":"post","link":"https:\/\/ixyzero.com\/blog\/archives\/3927.html","title":{"rendered":"Django\u4e2d\u7684request.POST\u548crequest.body"},"content":{"rendered":"<p>=Start=<\/p>\n<h4 id=\"id-\u6a21\u677f-\u7f18\u7531\uff1a\">\u7f18\u7531\uff1a<\/h4>\n<p>\u4e4b\u524d\u5176\u5b9e\u6ca1\u60f3\u8fc7Django\u4e2d\u7684request.POST\u548crequest.body\u6709\u4ec0\u4e48\u4e0d\u540c\uff0c\u6700\u8fd1\u8e29\u4e86\u4e9b\u5751\uff0c\u624d\u77e5\u9053\uff0c\u539f\u6765\u4e24\u8005\u8fd8\u662f\u6709\u533a\u522b\u7684\uff0c\u4e00\u4e0d\u5c0f\u5fc3\u5c31\u5bb9\u6613\u51fa\u9519\u3002<\/p>\n<p>\u6240\u4ee5\u5728\u6b64\u8bb0\u5f55\u4e00\u4e0b\uff0c\u65b9\u4fbf\u4ee5\u540e\u53c2\u8003\u3002<\/p>\n<h4 id=\"id-\u6a21\u677f-\u6b63\u6587\uff1a\">\u6b63\u6587\uff1a<\/h4>\n<h5 id=\"id-\u6a21\u677f-\u53c2\u8003\u89e3\u7b54\uff1a\">\u53c2\u8003\u89e3\u7b54\uff1a<\/h5>\n<p>\u4e0b\u9762\u662f<code>class HttpRequest(object)<\/code>\u4e2d\u83b7\u53d6<code>POST QueryDict<\/code>\u7684\u51fd\u6570\u90e8\u5206\uff1a<\/p>\n<pre class=\"lang:default decode:true \">def _load_post_and_files(self):\r\n    \"\"\"Populate self._post and self._files if the content-type is a form type\"\"\"\r\n    if self.method != 'POST':\r\n        self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()\r\n        return\r\n    if self._read_started and not hasattr(self, '_body'):\r\n        self._mark_post_parse_error()\r\n        return\r\n\r\n    if self.content_type == 'multipart\/form-data':\r\n        if hasattr(self, '_body'):\r\n            # Use already read data\r\n            data = BytesIO(self._body)\r\n        else:\r\n            data = self\r\n        try:\r\n            self._post, self._files = self.parse_file_upload(self.META, data)\r\n        except MultiPartParserError:\r\n            # An error occurred while parsing POST data. Since when\r\n            # formatting the error the request handler might access\r\n            # self.POST, set self._post and self._file to prevent\r\n            # attempts to parse POST data again.\r\n            # Mark that an error occurred. This allows self.__repr__ to\r\n            # be explicit about it instead of simply representing an\r\n            # empty POST\r\n            self._mark_post_parse_error()\r\n            raise\r\n    elif self.content_type == 'application\/x-www-form-urlencoded':\r\n        self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()\r\n    else:\r\n        self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()\r\n<\/pre>\n<p>\u8fd9\u91cc\u4e3b\u8981\u5173\u6ce8\u540e\u9762\u7684 <code>if elif else<\/code>\u8fd9\u4e09\u4e2a\u5206\u652f\u5373\u53ef\uff0c\u4ece <code>elif self.content_type == 'application\/x-www-form-urlencoded':<\/code>\u8fd9\u4e2a\u5206\u652f\u80fd\u770b\u5230<span style=\"color: #ff0000;\"><strong>\u53ea\u6709\u8bf7\u6c42header\u4e2d\u7684 <code>'Content-Type'\uff1a'application\/x-www-form-urlencoded'<\/code>\u624d\u4f1a\u586b\u5145request.POST\uff0c\u5176\u5b83\u60c5\u51b5\u4e0b\u53ea\u6709\u4e00\u4e2a\u7a7a\u7684 <code>&lt;QueryDict: {}&gt;<\/code>\u3002<\/strong><\/span><\/p>\n<p>\u6d4b\u8bd5\u3001\u9a8c\u8bc1\u5982\u4e0b\uff1a<\/p>\n<pre class=\"lang:default decode:true\" title=\"Django\u4e2d\u7684\u4e00\u4e2aview\u51fd\u6570\">from django.http import HttpResponse, HttpResponseBadRequest\r\nfrom django.views.decorators.csrf import csrf_exempt\r\nimport json\r\nimport traceback\r\n\r\n@csrf_exempt\r\ndef print_post_info(request):\r\n    if request.method != 'POST':\r\n        return HttpResponseBadRequest('unsupport method')\r\n    print 'request.content_type = {0}'.format(request.META.get('CONTENT_TYPE', ''))\r\n\r\n    try:\r\n        if request.META.get('CONTENT_TYPE', '') == 'application\/x-www-form-urlencoded':\r\n            received_json_data = request.POST\r\n        else:\r\n            received_json_data = json.loads(request.body)\r\n\r\n        print \"request.body::{0}====\".format(request.body)\r\n        print \"request.POST::{0}====\".format(request.POST)\r\n        print \"received_json_data::{0}====\".format(received_json_data)\r\n        return HttpResponse('\\nrequest.body: \"{0}\"\\nrequest.POST: \"{1}\"'.format(request.body, request.POST))\r\n    except Exception as e:\r\n        return HttpResponseBadRequest(traceback.format_exc())\r\n<\/pre>\n<p>urls.py\u7684\u914d\u7f6e\u5f88\u7b80\u5355\uff0c\u5728\u8fd9\u91cc\u6682\u4e14\u7565\u53bb\u3002\u4e0b\u9762\u662f\u7528curl\u53d1\u6d4b\u8bd5\u8bf7\u6c42\u7684\u547d\u4ee4\u53ca\u5176\u8fd4\u56de\uff1a<\/p>\n<pre class=\"lang:default decode:true\"># \u9ed8\u8ba4\u60c5\u51b5\u4e0b\uff0c\u662f\u4ee5Content-Type\u4e3a 'application\/x-www-form-urlencoded' \u53d1\u51fa\u7684POST\u8bf7\u6c42\r\n$ curl -X POST http:\/\/127.0.0.1:8080\/post -d 'short_name=unknown&amp;long_name=Administrator'\r\n\r\nrequest.body: \"short_name=unknown&amp;long_name=Administrator\"\r\nrequest.POST: \"&lt;QueryDict: {u'long_name': [u'Administrator'], u'short_name': [u'unknown']}&gt;\"\r\n\r\n# \u4e3b\u52a8\u5c06Content-Type\u4fee\u6539\u4e3a 'application\/json' \u6765\u53d1\u51fa\u9519\u8bef\u7684POST\u8bf7\u6c42\r\n$ curl -X POST http:\/\/127.0.0.1:8080\/post -H 'Content-Type: application\/json' -d 'short_name=unknown&amp;long_name=Administrator'\r\nTraceback (most recent call last):\r\n  File \"\/Users\/ixyzero\/Desktop\/python_web\/do_test_func\/download_file\/views.py\", line 35, in print_post_info\r\n    received_json_data = json.loads(request.body)\r\n  File \"\/System\/Library\/Frameworks\/Python.framework\/Versions\/2.7\/lib\/python2.7\/json\/__init__.py\", line 338, in loads\r\n    return _default_decoder.decode(s)\r\n  File \"\/System\/Library\/Frameworks\/Python.framework\/Versions\/2.7\/lib\/python2.7\/json\/decoder.py\", line 366, in decode\r\n    obj, end = self.raw_decode(s, idx=_w(s, 0).end())\r\n  File \"\/System\/Library\/Frameworks\/Python.framework\/Versions\/2.7\/lib\/python2.7\/json\/decoder.py\", line 384, in raw_decode\r\n    raise ValueError(\"No JSON object could be decoded\")\r\nValueError: No JSON object could be decoded\r\n\r\n# \u4e3b\u52a8\u5c06Content-Type\u4fee\u6539\u4e3a 'application\/json' \u6765\u53d1\u51fa\u6b63\u786e\u7684POST\u8bf7\u6c42\r\n$ curl -X POST http:\/\/127.0.0.1:8080\/post -H 'Content-Type: application\/json' -d '{\"short_name\": \"unknown\", \"long_name\": \"Administrator\"}'\r\n\r\nrequest.body: \"{\"short_name\": \"unknown\", \"long_name\": \"Administrator\"}\"\r\nrequest.POST: \"&lt;QueryDict: {}&gt;\"\r\n$<\/pre>\n<p>\u5bf9\u5e94\u7684Server\u7aef\u6536\u5230\u7684Content-Type\u5206\u522b\u662f\uff1a<\/p>\n<pre class=\"lang:default decode:true \">request.META.get('CONTENT_TYPE') == 'application\/x-www-form-urlencoded'\r\n\r\nrequest.META.get('CONTENT_TYPE') == 'application\/json'\r\n\r\nrequest.META.get('CONTENT_TYPE') == 'application\/json'<\/pre>\n<p><strong>\u51e0\u4e2a\u5fc3\u5f97\u3001\u6ce8\u610f\u4e8b\u9879\uff1a<\/strong><\/p>\n<ul>\n<li><strong>\u80fd\u7528 <code>.get('key_name')<\/code> \u65b9\u5f0f\u7684\u5c31\u4e0d\u8981\u7528 <code>['key_name']<\/code> \u7684\u65b9\u5f0f\uff1b<\/strong><\/li>\n<li><span style=\"color: #ff0000;\"><strong>\u5c06\u4efb\u4f55\u53ef\u80fd\u51fa\u73b0Exception\u7684\u5730\u65b9\u90fd\u653e\u5728\u5408\u9002\u7684try..catch\u4e2d\uff1b<\/strong><\/span><\/li>\n<li><span style=\"color: #ff0000;\"><strong>\u6d4b\u8bd5\u591a\u4e00\u70b9\uff0c\u95ee\u9898\u5c11\u4e00\u70b9\uff1b<\/strong><\/span><\/li>\n<li><strong>\u76d1\u63a7\u591a\u4e00\u70b9\uff0c\u7761\u5f97\u5b89\u5fc3\u70b9\uff1b<\/strong><\/li>\n<li><span style=\"color: #ff0000;\"><strong>\u5bf9\u6838\u5fc3\u63a5\u53e3\u4e00\u5b9a\u8981\u505a\u597d\u80fd\u529b\u5bb9\u91cf\u9884\u4f30\u3001\u7ba1\u7406\uff1b<\/strong><\/span><\/li>\n<li><strong>\u4e0d\u6015\u51fa\u9519\uff0c\u5c31\u6015\u51fa\u9519\u4e86\u8fd8\u4e0d\u77e5\u9053\u539f\u56e0\u5728\u54ea\uff1b<\/strong><\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<h5 id=\"id-\u6a21\u677f-\u53c2\u8003\u94fe\u63a5\uff1a\">\u53c2\u8003\u94fe\u63a5\uff1a<\/h5>\n<ul>\n<li><span style=\"color: #ff0000;\"><strong>Django\u7684request.POST\u83b7\u53d6\u4e0d\u5230\u5185\u5bb9\u7684\u539f\u56e0<\/strong><\/span><br \/>\n<a href=\"https:\/\/blog.csdn.net\/liuxingen\/article\/details\/54176205\">https:\/\/blog.csdn.net\/liuxingen\/article\/details\/54176205<\/a><\/li>\n<li>Django \u7684 request.body \u89e3\u7801<br \/>\n<a href=\"https:\/\/stackoverflow.com\/questions\/29780060\/trying-to-parse-request-body-from-post-in-django\">https:\/\/stackoverflow.com\/questions\/29780060\/trying-to-parse-request-body-from-post-in-django<\/a><br \/>\n<a href=\"https:\/\/stackoverflow.com\/questions\/29514077\/get-request-body-as-string-in-django\">https:\/\/stackoverflow.com\/questions\/29514077\/get-request-body-as-string-in-django<\/a><br \/>\n<a href=\"https:\/\/stackoverflow.com\/questions\/24771250\/python-import-json-json-loadsrequest-body-2-7-3-4\">https:\/\/stackoverflow.com\/questions\/24771250\/python-import-json-json-loadsrequest-body-2-7-3-4<\/a><\/li>\n<li><a href=\"https:\/\/stackoverflow.com\/questions\/5552555\/unicodedecodeerror-invalid-continuation-byte\">json.loads() \u89e3\u7801\u5931\u8d25 UnicodeDecodeError<\/a><\/li>\n<\/ul>\n<p>=END=<\/p>\n","protected":false},"excerpt":{"rendered":"<p>=Start= \u7f18\u7531\uff1a \u4e4b\u524d\u5176\u5b9e\u6ca1\u60f3\u8fc7Django\u4e2d\u7684request.POST\u548crequest.body\u6709\u4ec0\u4e48 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[23,7],"tags":[627,1130,1132,1131],"class_list":["post-3927","post","type-post","status-publish","format-standard","hentry","category-knowledgebase-2","category-programing","tag-django","tag-request-body","tag-request-meta","tag-request-post"],"views":9181,"_links":{"self":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/3927","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/comments?post=3927"}],"version-history":[{"count":2,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/3927\/revisions"}],"predecessor-version":[{"id":3950,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/3927\/revisions\/3950"}],"wp:attachment":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/media?parent=3927"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/categories?post=3927"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/tags?post=3927"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}