web-dev-qa-db-ja.com

Pythonリクエストを使用してJSONを投稿する

クライアントからサーバーへJSONをPOSTする必要があります。私はPython 2.7.1とsimplejsonを使っています。クライアントは要求を使用しています。サーバーはCherryPyです。ハードコードされたJSONをサーバーから取得できます(コードは表示されていません)が、JSONをサーバーにPOSTしようとすると、 "400 Bad Request"が返されます。

これが私のクライアントコードです。

data = {'sender':   'Alice',
    'receiver': 'Bob',
    'message':  'We did it!'}
data_json = simplejson.dumps(data)
payload = {'json_payload': data_json}
r = requests.post("http://localhost:8080", data=payload)

これがサーバーコードです。

class Root(object):

    def __init__(self, content):
        self.content = content
        print self.content  # this works

    exposed = True

    def GET(self):
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return simplejson.dumps(self.content)

    def POST(self):
        self.content = simplejson.loads(cherrypy.request.body.read())

何か案は?

452
Charles R

Requestsバージョン2.4.2以降では、代わりに呼び出しで 'json'パラメータを使用することができます。

>>> import requests
>>> r = requests.post('http://httpbin.org/post', json={"key": "value"})
>>> r.status_code
200
>>> r.json()
{'args': {},
 'data': '{"key": "value"}',
 'files': {},
 'form': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Connection': 'close',
             'Content-Length': '16',
             'Content-Type': 'application/json',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.4.3 CPython/3.4.0',
             'X-Request-Id': 'xx-xx-xx'},
 'json': {'key': 'value'},
 'Origin': 'x.x.x.x',
 'url': 'http://httpbin.org/post'}

編集:この機能は公式文書に追加されました。あなたはそれをここで見ることができます: ドキュメントを要求します

727
Zeyang Lin

ヘッダー情報が欠落していたことがわかります。次のように動作します。

url = "http://localhost:8080"
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)
310
Charles R

リクエスト2.4.2( https://pypi.python.org/pypi/requests )から、 "json"パラメータがサポートされています。 "Content-Type"を指定する必要はありません。だから短いバージョン:

requests.post('http://httpbin.org/post', json={'test': 'cheers'})
51
ZZY

もっと良い方法は:

url = "http://xxx.xxxx.xx"

datas = {"cardno":"6248889874650987","systemIdentify":"s08","sourceChannel": 12}

headers = {'Content-type': 'application/json'}

rsp = requests.post(url, json=datas, headers=headers)
15
ellen

Python 3.5以降で完璧に動作します

クライアント:

import requests
data = {'sender':   'Alice',
    'receiver': 'Bob',
    'message':  'We did it!'}
r = requests.post("http://localhost:8080", json={'json_payload': data})

サーバ:

class Root(object):

    def __init__(self, content):
        self.content = content
        print self.content  # this works

    exposed = True

    def GET(self):
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return simplejson.dumps(self.content)

    @cherrypy.tools.json_in()
    @cherrypy.tools.json_out()
    def POST(self):
        self.content = cherrypy.request.json
        return {'status': 'success', 'message': 'updated'}
0
Ruhil Jaiswal