Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python requests Post request data with Django

Tags:

python

django

I'm trying to send a simple post request to a very simple django server and can't wrap my head around why the post data isn't appearing in the requests post dictionary and instead its in the request body.

Client code:

    payload = {'test':'test'}
    headers = {'Content-type': 'application/json','Accept': 'text/plain'}
    url = "localhost:8000"
    print json.dumps(payload)
    r = requests.post(url,data=json.dumps(payload),headers=headers)

Server Code:

def submit_test(request):
    if request.method == 'POST':
          print 'Post: "%s"' % request.POST
          print 'Body: "%s"' % request.body
          return HttpResponse('')

What is printed out on the server is:

Post: "<QueryDict: {}>"
Body: "{"test": "test"}"

I've played around with the headers and sending the data as a straight dictionary and nothing seems to work.

Any ideas? Thanks!!

like image 966
Ryan Avatar asked Apr 17 '14 03:04

Ryan


People also ask

How do you receive data from a Django form with a POST request?

Using Form in a View In Django, the request object passed as parameter to your view has an attribute called "method" where the type of the request is set, and all data passed via POST can be accessed via the request. POST dictionary. The view will display the result of the login form posted through the loggedin.

What is request POST get in Django?

request. POST. get('sth') will return None if 'sth' is not in request. POST . Additionally, .get allows you to provide an additional parameter of a default value which is returned if the key is not in the dictionary.


2 Answers

The POST dictionary only contains the form-encoded data that was sent in the body of the request. The body attribute contains the raw body of the request as a string. Since you are sending json-encoded data it only shows up in the raw body attribute and not in POST.

Check out more info in the docs.

Try form-encoded data and you should see the values in the POST dict as well:

payload = {'test':'test'}
url = "localhost:8000"
requests.post(url, data=payload)
like image 58
Nick Rempel Avatar answered Oct 16 '22 02:10

Nick Rempel


Specifying a user-agent in the headers should enable Django to interpret the raw data of the body and to correctly populate the POST dictionary. The following should work:

payload = {'test': 'test'}
url = "http://localhost:8000"
headers = {'User-Agent': 'Mozilla/5.0'}
requests.post(url, data=payload, headers=headers)
like image 28
Ursidours Avatar answered Oct 16 '22 00:10

Ursidours