Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

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

Solution 2:

Give this a try...

//cherrypy

import json

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

//javascript

functionSendJson()
{
    varJSONObject = { changes: [] };
    JSONObject.changes.push({"sender": "Alice", "receiver": "Bob" }
            );

    // code for IE7+, Firefox, Chrome, Opera, Safariif(window.XMLHttpRequest)
        xmlhttp=newXMLHttpRequest();
    else// code for IE6, IE5
        xmlhttp=newActiveXObject('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

Post a Comment for "Sending Json Through Requests Module And Catching It Using Bottle.py And Cherrypy"