如何使用 Python 请求 POST JSON 数据? [英] How to POST JSON data with Python Requests?

查看:107
本文介绍了如何使用 Python 请求 POST JSON 数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 JSON 从客户端 POST 到服务器.我正在使用 Python 2.7.1 和 simplejson.客户端正在使用请求.服务器是 CherryPy.我可以从服务器获取硬编码的 JSON(代码未显示),但是当我尝试将 JSON POST 到服务器时,我收到400 Bad Request".

这是我的客户端代码:

data = {'sender': 'Alice','接收器':'鲍勃','message': '我们做到了!'}data_json = simplejson.dumps(data)有效载荷 = {'json_payload': data_json}r = requests.post("http://localhost:8080", data=payload)

这是服务器代码.

类根(对象):def __init__(self, content):self.content = 内容打印 self.content # 这有效暴露=真定义获取(自我):cherrypy.response.headers['Content-Type'] = 'application/json'返回 simplejson.dumps(self.content)def POST(自我):self.content = simplejson.loads(cherrypy.request.body.read())

有什么想法吗?

解决方案

从 Requests 2.4.2 版开始,您可以使用 json= 参数(需要字典)而不是 data=(在调用中接受一个字符串):

<预><代码>>>>进口请求>>>r = requests.post('http://httpbin.org/post', json={key": value"})>>>r.status_code200>>>r.json(){'参数':{},'数据':'{'键':'值'}','文件':{},'形式': {},'标题':{'接受':'*/*','接受编码':'gzip,放气','连接':'关闭','内容长度':'16','内容类型':'应用程序/json','Host': 'httpbin.org','用户代理':'python-requests/2.4.3 CPython/3.4.0','X-Request-Id': 'xx-xx-xx'},'json': {'key': 'value'},'起源':'x.x.x.x','url': 'http://httpbin.org/post'}

I need to POST a JSON from a client to a server. I'm using Python 2.7.1 and simplejson. The client is using Requests. The server is CherryPy. I can GET a hard-coded JSON from the server (code not shown), but when I try to POST a JSON to the server, I get "400 Bad Request".

Here is my client code:

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)

Here is the server code.

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())

Any ideas?

解决方案

Starting with Requests version 2.4.2, you can use the json= parameter (which takes a dictionary) instead of data= (which takes a string) in the call:

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

这篇关于如何使用 Python 请求 POST JSON 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆