VaidAbhishek
VaidAbhishek

Reputation: 6144

Sending JSON through requests module and catching it using bottle.py and cherrypy

I have a server which needs to be able to accept JSON and then process it and then send JSON back. The code at my server side is using bottle.py with cherrypy. The route in concern is the following:

@route ('/tagTweets', method='POST')
def tagTweets():

    response.content_type = 'application/json'

    # here I need to be able to parse JSON send along in this request.

For requesting this page and testing the functionality, I'm using requests module code:

The data that I have to send is list of tweets. The data is itself fetched from some server which returns list of tweets. For fetching tweets, I'm using requests.get and then using json method of response object. This is working fine. Now I after some processing on this, I have to send this json, just like I fetched to another server.

url     = "http://localhost:8080/tagTweets"
data    = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r       = requests.post(url, data=json.dumps(data), headers=headers)

I'm not able to figure out how to gain access to the json send along the request.

Upvotes: 1

Views: 7595

Answers (2)

Andrew Kloos
Andrew Kloos

Reputation: 4578

Give this a try...

//cherrypy

import json

@route ('/tagTweets', method='POST')
def tagTweets(UpdatedData=None):
    Data = json.loads(UpdatedData)

//javascript

function SendJson()
{
    var JSONObject = { changes: [] };
    JSONObject.changes.push({"sender": "Alice", "receiver": "Bob" }
            );

    // code for IE7+, Firefox, Chrome, Opera, Safari
    if(window.XMLHttpRequest)
        xmlhttp=new XMLHttpRequest();
    else// code for IE6, IE5
        xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            alert(xmlhttp.responseText);
        }
    }

    xmlhttp.open("POST","/tagTweets", true);
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(JSON.stringify(JSONObject));
}

Hope this helps.

Andrew

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121814

For a application/json POST, simply access request.json:

@route ('/tagTweets', method='POST')
def tagTweets():
     response.content_type = 'application/json'
     sender = request.json['sender']
     receiver = request.json['receiver']
     message = request.json['message']

Upvotes: 5

Related Questions