How to receive json data using HTTP POST request in Django 1.6?

本秂侑毒 提交于 2019-11-26 08:00:01

问题


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\')

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 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?


回答1:


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)



回答2:


For python3 you have to decode body first:

received_json_data = json.loads(request.body.decode("utf-8"))



回答3:


One way is to use ajax.

frontend (javascript):-

var data_to_send = {}; //push 'values to send' into this. $.ajax({
      ..... //other ajax attributes
      data: {'val': JSON.stringify(data_to_send)},
      ..... //other ajax attributes });

backend (views.py):-

def RecieveData(request):
      data = json.loads(request.POST.get('data')) //contains the front end variable 'data_to_send'
      ..... //code as per requirements



回答4:


Create a form with data as field of type CharField or TextField and validate the passed data. Similar SO Question



来源:https://stackoverflow.com/questions/24068576/how-to-receive-json-data-using-http-post-request-in-django-1-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!