Python 请求模块 - POST 失败 - 无效字符 'o'

Python requests module - POST failing - invalid character 'o'

我正在尝试将原始 curl 命令转换为使用 Python 请求模块,但没有成功。这是一个查询 JBoss Mgmt 接口的简单请求,但它没有正确解析我的 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 —— 在我看来,这看起来就像我最初尝试做的那样 —— 现在可以工作了

  1. 按照上面的 def readconfigfile(): 阅读 JSON 文件
  2. 根据上面的 def converttodictionary 转换为 json/dictionary:json.loads(lin)
  3. 使用json.dumps和POST将这个json"back"转换为字符串

    payload = json.dumps(command)
    
    r = session.post(url, payload,auth=HTTPDigestAuth('brenn', '!12rori')
    

)