【问题标题】:Sending JSON through requests module and catching it using bottle.py and cherrypy通过 requests 模块发送 JSON 并使用 bottle.py 和 cherrypy 捕获它
【发布时间】:2013-01-31 10:48:56
【问题描述】:

我有一个服务器,它需要能够接受 JSON,然后对其进行处理,然后将 JSON 发回。我服务器端的代码使用 bottle.py 和 cherrypy。关注的路线如下:

@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.

为了请求此页面并测试功能,我使用 requests 模块代码:

我必须发送的数据是推文列表。数据本身是从某个返回推文列表的服务器获取的。对于获取推文,我使用requests.get,然后使用响应对象的 json 方法。这工作正常。现在我在对此进行了一些处理之后,我必须发送这个 json,就像我提取到另一个服务器一样。

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)

我无法弄清楚如何获得对随请求发送的 json 的访问权限。

【问题讨论】:

    标签: python json cherrypy bottle python-requests


    【解决方案1】:

    对于application/json POST,只需访问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']
    

    【讨论】:

    • 亲爱的 Martijn,我正在使用带有 bottle.py 的cherrypy。服务器运行命令是这样的:run(host='0.0.0.0', port=8082, server='cherrypy') request.json 由于某种原因输出为 NONE
    • @VaidAbhishek:在这种情况下,CherryPy 只是另一个 WSGI 服务器;你用的是什么版本的瓶子? request.body.read() 带给你什么?
    【解决方案2】:

    试试这个...

    //樱桃树

    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));
    }
    

    希望这会有所帮助。

    安德鲁

    【讨论】:

    • 只是一个变量名。可以是任何东西。哦 - 没有将它添加到cherrypy处理程序中......我现在将编辑我的答案。
    • 如果您使用的是 POST 那么为什么要在查询字符串中发送数据!
    • 啊-感谢您的评论。我已经阅读了更多关于 XMLHttpRequest 的内容并相应地更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2018-12-02
    • 2022-09-26
    • 1970-01-01
    • 2012-10-11
    • 2022-01-07
    • 2021-09-22
    • 2015-10-04
    • 1970-01-01
    相关资源
    最近更新 更多