Python 如何在 Django 1.6 中使用 HTTP POST 请求接收 json 数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24068576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to receive json data using HTTP POST request in Django 1.6?
提问by Alok Singh Mahor
I am learning Django1.6.
I want to post some JSONusing HTTP POST request and I am using Django for this task for learning.
I tried to use request.POST['data'], request.raw_post_data, request.bodybut none are working for me.
my views.py is
我正在学习Django1.6。
我想使用 HTTP POST 请求发布一些JSON,我正在使用 Django 来完成这项学习任务。
我尝试使用request.POST['data'], request.raw_post_data,request.body但没有一个对我有用。
我的 views.py 是
import json
from django.http import StreamingHttpResponse
def main_page(request):
if request.method=='POST':
received_json_data=json.loads(request.POST['data'])
#received_json_data=json.loads(request.body)
return StreamingHttpResponse('it was post request: '+str(received_json_data))
return StreamingHttpResponse('it was GET request')
I am posting JSON data using requestsmodule.
我正在使用请求模块发布 JSON 数据。
import requests
import json
url = "http://localhost:8000"
data = {'data':[{'key1':'val1'}, {'key2':'val2'}]}
headers = {'content-type': 'application/json'}
r=requests.post(url, data=json.dumps(data), headers=headers)
r.text
r.textshould print that message and posted data but I am not able to solve this simple problem. please tell me how to collect posted data in Django 1.6?
r.text应该打印该消息并发布数据,但我无法解决这个简单的问题。请告诉我如何在 Django 1.6 中收集发布的数据?
采纳答案by Daniel Roseman
You're confusing form-encoded and JSON data here. request.POST['foo']is for form-encoded data. You are posting raw JSON, so you should use request.body.
您在这里混淆了表单编码和 JSON 数据。request.POST['foo']用于表单编码数据。您正在发布原始 JSON,因此您应该使用request.body.
received_json_data=json.loads(request.body)
回答by Kracekumar
Create a form with data as field of type CharFieldor TextFieldand validate the passed data. Similar SO Question
创建具有数据类型的字段的表单CharField或TextField并验证传递的数据。类似的问题
回答by Thran
For python3 you have to decode body first:
对于python3,您必须先解码主体:
received_json_data = json.loads(request.body.decode("utf-8"))

