Опубликовать JSON с использованием запросов Python - PullRequest
475 голосов
/ 16 марта 2012

Мне нужно отправить JSON с клиента на сервер. Я использую Python 2.7.1 и simplejson. Клиент использует запросы. Сервер является CherryPy. Я могу получить жестко закодированный JSON с сервера (код не показан), но когда я пытаюсь отправить JSON на сервер, я получаю «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())

Есть идеи?

Ответы [ 6 ]

769 голосов
/ 13 октября 2014

Начиная с версии запросов 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'}

РЕДАКТИРОВАТЬ: Эта функция была добавлена ​​в официальную документацию. Вы можете просмотреть его здесь: Запрос документации

323 голосов
/ 31 марта 2012

Оказывается, мне не хватало информации заголовка. Следующие работы:

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)
54 голосов
/ 10 декабря 2014

Из запросов 2.4.2 (https://pypi.python.org/pypi/requests), поддерживается параметр "json". Не нужно указывать "Content-Type". Поэтому более короткая версия:

requests.post('http://httpbin.org/post', json={'test': 'cheers'})
18 голосов
/ 04 мая 2017

Лучший способ :

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)
0 голосов
/ 21 января 2017

Отлично работает с 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 голосов
/ 13 октября 2016

Это прекрасно работает для Python версии 3.5, если URL содержит строку запроса / значение параметра,

URL запроса = https://baaaah2.com/ws/rest/v1/concept/

Значение параметра = 21f6bb43-98a1-419d-8f0c-8133669e40ca

import requests
r = requests.post('https://baaaah2.com/ws/rest/v1/concept/21f6bb43-98a1-419d-8f0c-8133669e40ca',auth=('username', 'password'),verify=False, json={"name": "Value"})
headers = {'Content-type': 'application/json'}
print(r.status_code)
...