我正在尝试将原始 curl 命令转换为使用 Python 请求模块,但没有成功。这是一个查询 JBoss Mgmt 接口(interface)的简单请求,但它没有正确解析我的 JSON。
16:34:26,868 DEBUG [org.jboss.as.domain.http.api] (HttpManagementService-threads - 15) Unable to construct ModelNode 'Invalid character: o'
Python 版本
Python 2.7.6
工作的原始 cURL 命令:
/usr/bin/curl --digest -v -L -D - 'http://brenn:!12rori@localhost:9990/management' --header Content-Type:application/json '-d {"operation":"read-attribute","name":"server-state","json.pretty":1}'
在 python 代码中,我像这样读入我的 REST/cURL 负载
import requests
----
def readconfigfile():
with open('jboss_modification.cfg') as f:
lines = f.readlines()
return lines
配置文件看起来是这样的
{"operation":"read-attribute","name":"server-state","json.pretty":1}
我将 str 格式从 readconfigfile() 转换为字典,如下所示
def converttodictionary(incominglines):
commands = []
for lin in incominglines:
#dumps = json.dumps(lin)
obj = json.loads(lin)
commands.append(obj)
return commands
执行这个请求的python代码如下
def applyconfig(lines):
url="http://localhost:9990/management"
auth=HTTPBasicAuth('brenn', '!12rori')
s = requests.Session()
re=s.get(url, auth=HTTPDigestAuth('brenn', '!12rori')) ##200 RESP
s.headers.update({'Content-Type': 'application/json'})
for line in lines:
payload=line
r=s.post(url,payload)
print(r.text)
非常感谢任何帮助?
注意:这个问题已经更新了几次,因为我解决了其他问题....
最佳答案
问题是...
初始 JSON 请求失败,因为当我从 python 解释为 str 的文件中读取它时。
使用 json.loads 转换为字典,服务器接受了请求,但无法解析带有非法字符错误的 JSON
使用 json.dumps 将此 json 转换回 str——在我看来,这看起来就像我最初尝试做的——现在可以工作了
- 按照上面的
def readconfigfile():
读取 JSON 文件 - 按照上面的
def converttodictionary
转换为 json/dictionary:json.loads(lin)
使用
json.dumps
和 POST 将此 json“返回”为字符串,如下所示payload = json.dumps(command) r = session.post(url, payload,auth=HTTPDigestAuth('brenn', '!12rori')
)
关于Python 请求模块 - POST 失败 - 无效字符 'o',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35042753/