Сообщение JSON с использованием запросов Python
Мне нужно отправить JSON с клиента на сервер. Я использую Python 2.7.1 и simplejson. Клиент использует Запросы. Сервер CherryPy. Я могу получить JSON с жестким кодом с сервера (код не показан), но когда я пытаюсь выполнить POST 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())
Любые идеи?
Ответы
Ответ 1
Начиная с версии 2.4.2 Requests, вы можете альтернативно использовать параметр 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'}
ОБНОВЛЕНИЕ: эта функция была добавлена в официальную документацию. Вы можете просмотреть его здесь: Запрос документации
Ответ 2
Оказывается, мне не хватает информации заголовка. Следующие работы:
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)
Ответ 3
Из запросов 2.4.2 (https://pypi.python.org/pypi/requests) поддерживается параметр "json". Не нужно указывать "Content-Type". Таким образом, более короткая версия:
requests.post('http://httpbin.org/post', json={'test': 'cheers'})
Ответ 4
Лучший способ:
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)
Ответ 5
Работает отлично с 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'}
Ответ 6
Это прекрасно работает для Python версии 3.5,
Если URL содержит значение Query String/Parameter,
URL запроса = https://baaaah2.com/ws/rest/v1/concept/
Значение параметра = 21f6bb43
import requests
headers = {'Content-type': 'application/json'}
result = requests.post('https://baaaah2.com/ws/rest/v1/concept/21f6bb43',auth=('username', 'password'),verify=False, headers=headers)
print(result.status_code)