关于解析从 python 2.x in Python 3.x 返回的 HTTPResponse
Regarding parsing HTTPResponse returned from python 2.x in Python 3.x
我是 Python 的新手。我在 python 3.x 和 python 2.x 中都有一个代码(实际上,它是一个用 2.x 编写的库)。我正在从 python 3.x 调用 python 2.x 中的一个函数。库 return 一个 HTTPResponse(来自 python 2.x)。我无法在我的代码中解析 HTTPResponse(在 Python 3.x 中)。
我的要求是:
jsonData = {'string': post_message_data['Message']}
url = "%s/testurl/" % (settings.STIX_API_URL)
response = requests.post(url, jsonData)
正在处理请求 Python 2.x
在 python 2.x 中,我正在处理此请求并发回 http 响应,它是从电子邮件中解析的纯文本回复。
htmldata = request.body
strdata = json.loads(htmldata)
html = strdata['string']
reply = quotations.extract_from(html, 'text/html')
reply = quotations.extract_from_html(html)
return HttpResponse(json.dumps({'reply':reply}), mimetype='application/json')
现在我的问题是"how to get that json data in json format in the function called in 3.x"
我试过response.read()、response.readall()、response.content。每次得到不同的错误。
Python 的版本与这个问题完全无关。
您从 requests.post
调用获得的响应有一个 json()
方法,其中 returns 内容作为已解析的 Python 数据结构。
我从请求发送 JSON 数据时出现问题。它的格式不正确。这就是为什么在 HTTPResponse
对象中我得到 500 Internal server error (No JSON can be decoded)。我在检查 response.content
时发现了这个错误
之后,我正确编码了 JSON 并从响应对象获得了 JSON 格式的正确输出。正如 Martijn 所说,使用 response.json()
.
我是 Python 的新手。我在 python 3.x 和 python 2.x 中都有一个代码(实际上,它是一个用 2.x 编写的库)。我正在从 python 3.x 调用 python 2.x 中的一个函数。库 return 一个 HTTPResponse(来自 python 2.x)。我无法在我的代码中解析 HTTPResponse(在 Python 3.x 中)。
我的要求是:
jsonData = {'string': post_message_data['Message']}
url = "%s/testurl/" % (settings.STIX_API_URL)
response = requests.post(url, jsonData)
正在处理请求 Python 2.x
在 python 2.x 中,我正在处理此请求并发回 http 响应,它是从电子邮件中解析的纯文本回复。
htmldata = request.body
strdata = json.loads(htmldata)
html = strdata['string']
reply = quotations.extract_from(html, 'text/html')
reply = quotations.extract_from_html(html)
return HttpResponse(json.dumps({'reply':reply}), mimetype='application/json')
现在我的问题是"how to get that json data in json format in the function called in 3.x"
我试过response.read()、response.readall()、response.content。每次得到不同的错误。
Python 的版本与这个问题完全无关。
您从 requests.post
调用获得的响应有一个 json()
方法,其中 returns 内容作为已解析的 Python 数据结构。
我从请求发送 JSON 数据时出现问题。它的格式不正确。这就是为什么在 HTTPResponse
对象中我得到 500 Internal server error (No JSON can be decoded)。我在检查 response.content
之后,我正确编码了 JSON 并从响应对象获得了 JSON 格式的正确输出。正如 Martijn 所说,使用 response.json()
.