Jak publikować dane JSON za pomocą zapytań Pythona?

Muszę opublikować JSON z Klienta na serwer. Używam Pythona 2.7.1 i simplejson. Klient korzysta z żądań. Serwerem jest CherryPy. Mogę uzyskać kodowany na twardo JSON z serwera( kod nie jest pokazany), ale kiedy próbuję wysłać JSON na serwer, dostaję "400 Bad Request".

Oto Mój kod klienta:

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)

Oto kod serwera.

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())
Jakieś pomysły?
Author: ivanleoncz, 2012-03-16

6 answers

Począwszy od wersji 2.4.2, można użyć json= parametr (który pobiera słownik) zamiast data= (który pobiera ciąg znaków) w wywołaniu:

>>> 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'}
 1240
Author: Zeyang Lin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-12 18:12:41

Okazało się, że brakowało mi informacji nagłówka. Następujące utwory:

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)
 401
Author: Charles R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-01 18:43:12

From requests 2.4.2 (https://pypi.python.org/pypi/requests ), parametr "json" jest obsługiwany. Nie trzeba określać "Content-Type". Więc krótsza wersja:

requests.post('http://httpbin.org/post', json={'test': 'cheers'})
 75
Author: ZZY,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-22 03:11:09

The better way is:

url = "http://xxx.xxxx.xx"
data = {
    "cardno": "6248889874650987",
    "systemIdentify": "s08",
    "sourceChannel": 12
}
resp = requests.post(url, json=data)
 38
Author: ellen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-10-02 23:22:17

Który parametr pomiędzy (data / JSON / files ) powinien być użyty, to zależy od nagłówka żądania o nazwie ContentType (Zwykle sprawdź to za pomocą narzędzi programistycznych Twojej przeglądarki),

Gdy Content-Type to application / x-www-form-urlencoded, kod powinien być:

requests.post(url, data=jsonObj)

Gdy Content-Type to application / json, Twój kod powinien być jednym z poniższych:

requests.post(url, json=jsonObj)
requests.post(url, data=jsonstr, headers={"Content-Type":"application/json"})

Gdy Content-Type to multipart / form-data, służy do przesyłania plików, więc Twój kod powinien be:

requests.post(url, files=xxxx)
 16
Author: xiaoming,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-28 01:11:44

Działa doskonale z Pythonem 3.5 +

Klient:

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

Serwer:

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'}
 5
Author: Ruhil Jaiswal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-20 21:29:45