在 Python 中检索 JSON 以响应 POST
Retrieving JSON in Python in response to POST
我正在尝试从服务器获取 JSON 以在 Python 代码中使用它。出于测试目的,我通过 curl
:
做了 POST
$ curl -u trial:trial -H "Content-Type: application/json"
-X POST -d '{"BP_TSM":"22"}' http://some-host --trace-ascii -
我的 Java 代码似乎可以正确处理创建 JSON 作为响应。请查看curl
命令的结果:
== Info: About to connect() to localhost port 8080 (#0)
== Info: Trying ::1...
== Info: Connected to localhost (::1) port 8080 (#0)
== Info: Server auth using Basic with user 'trial'
=> Send header, 224 bytes (0xe0)
0000: POST /get/auth HTT
0040: P/1.1
0047: Authorization: Basic dHJpYWw6dHJpYWw=
006e: User-Agent: curl/7.29.0
0087: Host: localhost:8080
009d: Accept: */*
00aa: Content-Type: application/json
00ca: Content-Length: 15
00de:
=> Send data, 15 bytes (0xf)
0000: {"BP_TSM":"22"}
== Info: upload completely sent off: 15 out of 15 bytes
<= Recv header, 23 bytes (0x17)
0000: HTTP/1.1 202 Accepted
<= Recv header, 34 bytes (0x22)
0000: Server: Payara Micro #badassfish
<= Recv header, 32 bytes (0x20)
0000: Content-Type: application/json
<= Recv header, 37 bytes (0x25)
0000: Date: Thu, 22 Mar 2018 14:30:43 GMT
<= Recv header, 21 bytes (0x15)
0000: Content-Length: 108
<= Recv header, 29 bytes (0x1d)
0000: X-Frame-Options: SAMEORIGIN
<= Recv header, 2 bytes (0x2)
0000:
<= Recv data, 108 bytes (0x6c)
0000: {"title":"Free Music Archive - Albums","message":"","total":"112
0040: 59","total_pages":2252,"page":1,"limit":"5"}
{"title":"Free Music Archive - Albums","message":"","total":"11259","total_pages
":2252,"page":1,"limit":"5"}== Info: Connection #0 to host localhost left intact
现在我希望 Python 脚本能够收到与 curl
相同的消息。我写了以下 Python 代码(注意我不是 Python 开发人员):
import pickle
import requests
import codecs
import json
from requests.auth import HTTPBasicAuth
from random import randint
req = requests.get('server/get/auth', auth=HTTPBasicAuth('trial', 'trial'))
return pickle.dumps(req)
不幸的是,当执行 return pickle.dumps(req)
命令时,我收到错误消息 'unicode' object has no attribute 'copy'
。我也尝试使用 return json.dumps(req)
但这次我得到另一个错误:
Traceback (most recent call last):
File "/tmp/tmp8DfLJ7/usercode.py", line 16, in the_function
return json.dumps(req)
File "/usr/lib64/python2.7/json/__init__.py", line 244, in dumps
return _default_encoder.encode(obj)
File "/usr/lib64/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib64/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/usr/lib64/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Response [405]> is not JSON serializable
我的 Python 代码是否有错误,或者是我的 Java 服务器返回错误 JSON 的错误?
您可以使用 requests.json()
方法将 json 响应作为字典
req = requests.get('http://yourdomain.com/your/path', auth=HTTPBasicAuth('trial', 'trial'))
mydict = req.json()
您正在尝试转储 Response
对象。
尝试返回 req.json()
或致电 json.loads(req.text)
为了加载 Json 字符串,您需要使用 json.loads(req.text)
.
您还必须确保请求字符串有效 json。
例如
'{"FOO":"BAR"}'
您的 Python 代码中存在一些错误。
- 您正在使用
request.get
至 POST。相反,使用 request.post
.
- 您没有将
BP_TSM
json 字符串传递到您的请求中。在 request.post
. 中使用 data=
- 您没有模拟
-H
切换到 curl。在 request.post
. 中使用 headers=
- 您正在无缘无故地使用
pickle
。不要那样做。
- 当您不在函数中时,您正在使用
return
语句。不要那样做。如果要打印到标准输出,请改用 print()
或 sys.stdout.write()
。
- 如果你真的想使用从 JSON 返回的变量(而不是简单地打印到标准输出),你应该调用
req.json()
.
这是解决了问题的代码版本。
import requests
import json
import sys
from requests.auth import HTTPBasicAuth
data = '{"BP_TSM": "22"}' # curl -d
headers = {'content-type': 'application/json'} # curl -H
auth = HTTPBasicAuth('trial', 'trial') # curl -u
req = requests.post( # curl -X POST
'http://httpbin.org/post',
auth=auth,
data=data,
headers=headers)
sys.stdout.write(req.text) # Display JSON on stdout
returned_data = req.json()
my_ip = returned_data["origin"] # Query value from JSON
print("My public IP is", my_ip)
我正在尝试从服务器获取 JSON 以在 Python 代码中使用它。出于测试目的,我通过 curl
:
POST
$ curl -u trial:trial -H "Content-Type: application/json"
-X POST -d '{"BP_TSM":"22"}' http://some-host --trace-ascii -
我的 Java 代码似乎可以正确处理创建 JSON 作为响应。请查看curl
命令的结果:
== Info: About to connect() to localhost port 8080 (#0)
== Info: Trying ::1...
== Info: Connected to localhost (::1) port 8080 (#0)
== Info: Server auth using Basic with user 'trial'
=> Send header, 224 bytes (0xe0)
0000: POST /get/auth HTT
0040: P/1.1
0047: Authorization: Basic dHJpYWw6dHJpYWw=
006e: User-Agent: curl/7.29.0
0087: Host: localhost:8080
009d: Accept: */*
00aa: Content-Type: application/json
00ca: Content-Length: 15
00de:
=> Send data, 15 bytes (0xf)
0000: {"BP_TSM":"22"}
== Info: upload completely sent off: 15 out of 15 bytes
<= Recv header, 23 bytes (0x17)
0000: HTTP/1.1 202 Accepted
<= Recv header, 34 bytes (0x22)
0000: Server: Payara Micro #badassfish
<= Recv header, 32 bytes (0x20)
0000: Content-Type: application/json
<= Recv header, 37 bytes (0x25)
0000: Date: Thu, 22 Mar 2018 14:30:43 GMT
<= Recv header, 21 bytes (0x15)
0000: Content-Length: 108
<= Recv header, 29 bytes (0x1d)
0000: X-Frame-Options: SAMEORIGIN
<= Recv header, 2 bytes (0x2)
0000:
<= Recv data, 108 bytes (0x6c)
0000: {"title":"Free Music Archive - Albums","message":"","total":"112
0040: 59","total_pages":2252,"page":1,"limit":"5"}
{"title":"Free Music Archive - Albums","message":"","total":"11259","total_pages
":2252,"page":1,"limit":"5"}== Info: Connection #0 to host localhost left intact
现在我希望 Python 脚本能够收到与 curl
相同的消息。我写了以下 Python 代码(注意我不是 Python 开发人员):
import pickle
import requests
import codecs
import json
from requests.auth import HTTPBasicAuth
from random import randint
req = requests.get('server/get/auth', auth=HTTPBasicAuth('trial', 'trial'))
return pickle.dumps(req)
不幸的是,当执行 return pickle.dumps(req)
命令时,我收到错误消息 'unicode' object has no attribute 'copy'
。我也尝试使用 return json.dumps(req)
但这次我得到另一个错误:
Traceback (most recent call last):
File "/tmp/tmp8DfLJ7/usercode.py", line 16, in the_function
return json.dumps(req)
File "/usr/lib64/python2.7/json/__init__.py", line 244, in dumps
return _default_encoder.encode(obj)
File "/usr/lib64/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib64/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/usr/lib64/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Response [405]> is not JSON serializable
我的 Python 代码是否有错误,或者是我的 Java 服务器返回错误 JSON 的错误?
您可以使用 requests.json()
方法将 json 响应作为字典
req = requests.get('http://yourdomain.com/your/path', auth=HTTPBasicAuth('trial', 'trial'))
mydict = req.json()
您正在尝试转储 Response
对象。
尝试返回 req.json()
或致电 json.loads(req.text)
为了加载 Json 字符串,您需要使用 json.loads(req.text)
.
您还必须确保请求字符串有效 json。
例如
'{"FOO":"BAR"}'
您的 Python 代码中存在一些错误。
- 您正在使用
request.get
至 POST。相反,使用request.post
. - 您没有将
BP_TSM
json 字符串传递到您的请求中。在request.post
. 中使用 - 您没有模拟
-H
切换到 curl。在request.post
. 中使用 - 您正在无缘无故地使用
pickle
。不要那样做。 - 当您不在函数中时,您正在使用
return
语句。不要那样做。如果要打印到标准输出,请改用print()
或sys.stdout.write()
。 - 如果你真的想使用从 JSON 返回的变量(而不是简单地打印到标准输出),你应该调用
req.json()
.
data=
headers=
这是解决了问题的代码版本。
import requests
import json
import sys
from requests.auth import HTTPBasicAuth
data = '{"BP_TSM": "22"}' # curl -d
headers = {'content-type': 'application/json'} # curl -H
auth = HTTPBasicAuth('trial', 'trial') # curl -u
req = requests.post( # curl -X POST
'http://httpbin.org/post',
auth=auth,
data=data,
headers=headers)
sys.stdout.write(req.text) # Display JSON on stdout
returned_data = req.json()
my_ip = returned_data["origin"] # Query value from JSON
print("My public IP is", my_ip)