问题描述
我正在学习 1.6。
我想发布一些使用HTTP POST请求,我正在使用Django进行此任务的学习。
我试图使用请求.POST ['data']
, request.raw_post_data
, request.body
但没有正在为我工作。
我的views.py是
I am learning Django 1.6.
I want to post some JSON using 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.body
but none are working for me.
my views.py is
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')
我使用 modu乐。
I am posting JSON data using requests module.
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.text
应该打印该消息并发布数据,但是我无法解决这个简单的问题。请告诉我如何在Django 1.6中收集发布的数据?
r.text
should 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?
推荐答案
这里您可能会混淆表单编码和JSON数据。 request.POST ['foo']
用于表单编码数据。您正在发布原始的JSON,因此您应该使用 request.body
。
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
.
received_json_data=json.loads(request.body)
这篇关于如何使用Django 1.6中的HTTP POST请求接收json数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!