cur_ques_details
уже является объектом JS, вам не нужно его анализировать
Как и в случае с запросами версии 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'}
EDIT: эта функция добавлена в официальную документацию , Вы можете просмотреть его здесь: Документация запросов
Лучший способ:
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)
Оказывается, мне не хватает информации заголовка. Следующие работы:
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)
application/json
в GET
и почему-то пропустил то, что вы не предоставили его по запросу. Вам также может потребоваться убедиться, что вы вернете что-то из POST
, или вы можете получить 500
.
– Nick Bastin
31 March 2012 в 05:01
Это отлично работает для Python версии 3.5, если URL содержит значение строки запроса / параметра,
URL-адрес запроса = https://bah2.com/ws/rest/v1/concept/
Значение параметра = 21f6bb43-98a1-419d-8f0c-8133669e40ca
import requests
r = requests.post('https://bah2.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)
отлично работает с 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'}
Из запросов 2.4.2 ( https://pypi.python.org/pypi/requests ) поддерживается параметр «json». Не нужно указывать «Content-Type». Итак, более короткая версия:
requests.post('http://httpbin.org/post', json={'test': 'cheers'})
json
абсолютно ничего нет. Я должен был пойти в Гитуб, прежде чем я увидел какое-либо упоминание об этом: github.com/kennethreitz/requests/blob/… – IAmKale 30 April 2015 в 21:35