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

微笑、不失礼 提交于 2019-11-30 16:18:32

问题


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.


回答1:


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']



回答2:


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



来源:https://stackoverflow.com/questions/14895084/sending-json-through-requests-module-and-catching-it-using-bottle-py-and-cherryp

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