Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get POST data from request?

I just set up an apache server with django, and to test it, made a very simple function in views.py

channel = rabbit_connection()
@csrf_protect
@csrf_exempt
def index(request): 
    data={'text': 'Food truck is awesome! ', 'email': '[email protected]', 'name': 'Bob'}
    callback(json.dumps(data))   
    context = RequestContext(request)    
    return render_to_response('index.html', context_instance=context)

This function works fine if I send a GET or POST request to the server. However I would like to get this data from POST request. Assuming I send request like this:

import pycurl
import simplejson as json

data = json.dumps({'name':'Bob', 'email':'[email protected]', 'text': u"Food truck is awesome!"})

c = pycurl.Curl()
c.setopt(c.URL, 'http://ec2-54-......compute-1.amazonaws.com/index.html')
c.setopt(c.POSTFIELDS, data)
c.setopt(c.VERBOSE, True)

for i in range(100):
    c.perform()

What I would like to have in the view is something like this:

 if request.method == 'POST':
     data = ?????? # Something that will return me my dictionary

Just in case: It is always will be in JSON format and the fields are unknown.

like image 596
Vor Avatar asked Jul 02 '13 19:07

Vor


People also ask

Can we fetch data from POST API?

POST request using fetch API:To do a POST request we need to specify additional parameters with the request such as method, headers, etc. In this example, we'll do a POST request on the same JSONPlaceholder and add a post in the posts. It'll then return the same post content with an ID.

What is POST request data?

In computing, POST is a request method supported by HTTP used by the World Wide Web. By design, the POST request method requests that a web server accept the data enclosed in the body of the request message, most likely for storing it. It is often used when uploading a file or when submitting a completed web form.


2 Answers

data= request.POST.get('data','')

Will return you a single value (key=data) from your dictionary. If you want the entire dictionary, you simply use request.POST. You are using the QueryDict class here:

In an HttpRequest object, the GET and POST attributes are instances of django.http.QueryDict. QueryDict is a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably , pass multiple values for the same key.

QueryDict instances are immutable, unless you create a copy() of them. That means you can’t change attributes of request.POST and request.GET directly.

-Django Docs

like image 161
JcKelley Avatar answered Sep 18 '22 14:09

JcKelley


If the data posted is in JSON format, you need to deserialize it:

import simplejson
myDict = simplejson.loads(request.POST.get('data'))
like image 35
Rao Avatar answered Sep 21 '22 14:09

Rao