1

JSONを受け入れて処理し、JSONを送り返す必要があるサーバーがあります。私のサーバー側のコードは、cherrypyでbottle.pyを使用しています。問題のルートは次のとおりです。

@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.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にアクセスする方法がわかりません。

4

2 に答える 2

5

application/jsonPOST の場合は、以下にアクセスするだけです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']
于 2013-02-15T12:54:09.893 に答える
0

これを試してみてください...

//チェリーピー

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

お役に立てれば。

アンドリュー

于 2013-02-15T13:15:59.450 に答える