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

标签 python python-2.7 rest curl jboss

我正在尝试将原始 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——在我看来,这看起来就像我最初尝试做的——现在可以工作了

  1. 按照上面的 def readconfigfile(): 读取 JSON 文件
  2. 按照上面的 def converttodictionary 转换为 json/dictionary:json.loads(lin)
  3. 使用 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/

相关文章:

rest - 如何使用 FOSRestBundle 在 REST API 中处理实体更新(PUT 请求)

python - 读取 CSV 获取行数和 CSV 的前两行

python - Django 1.4 : return HTML in function

python - cv2.line 和 cv2.circle 返回 None

rest - 这是 Box API v2 获取事件时的错误吗

asp.net - 无法在 Azure 网站上使用 POST

python - 触发事件和执行实际事件的更好逻辑?

python - python中的循环和分支

python - 如何将 SimpleGUI 与 Python 2.7 和 3.0 shell 集成

python - 在 python 中迭代 JSON 对象