【问题标题】:python requests error check-mk APIpython请求错误检查-mk API
【发布时间】:2018-08-29 19:56:06
【问题描述】:

我正在尝试通过 Python 请求将字典数据添加到我们的 check-mk Web API,但我不断收到缺少键的错误:

{"result": "Check_MK exception: Missing required key(s): aux_tags, tag_groups", "result_code": 1}

这是我的代码:

import json
import requests

params_get = (
    ('action', 'get_hosttags'),
    ('_username', 'user'),
    ('_secret', 'secret'),
    ('request_format', 'json'),
)

params_set = (
    ('action', 'set_hosttags'),
    ('_username', 'user'),
    ('_secret', 'secret'),
    ('request_format', 'json'),
)

url = 'http://monitoringtest.local.domain/test/check_mk/webapi.py'

tags = ['tag1', 'tag2']

response_data = requests.get(url, params=params_get)
data = response_data.json()

new_data_tags = data['result']['tag_groups']
new_data = data['result']

# new_tags = []

for tag in tags:
    new_data['aux_tags'].append({'id': tag, 'title': 'tags in datacenter'})
    # new_tags.extend([{'aux_tags': [], 'id': tag, 'title': tag.upper() + ' Tag'}])

# all_tags = new_data_tags.extend([{'tags': new_tags, 'id': 'group1', 'title': 'tags in datacenter'}])

json.dump(data['result'], open("new_file", "w"))
response_data_new = requests.get(url, params=params_set, json=json.dumps(data['result']))
# response_data_new = requests.put(url, params=params_set)
# requests.post(url, params=params_set)
print(response_data_new.text)

# print(data['result'])
# json.dump(data['result'], open("new_file", "w"))

当我使用 curl 时,每件事都可以正常运行并显示成功消息:

{"result": null, "result_code": 0}

您知道导致错误的原因吗? 谢谢

【问题讨论】:

  • "Missing required key(s): aux_tags, tag_groups"" 您是否尝试将缺少的密钥添加到您的请求中?似乎您尝试将aux_tags 添加到new_data,但new_data实际请求中没有用到
  • 密钥没有丢失,它们在文件new_file 中,当我复制内容并使用 curl 将其发送到 API 时,它可以工作。在我看来,这是一个解析问题。
  • 文件与请求无关,发送请求后打开文件。 curl 请求必须在做其他事情。如果你添加你正在使用的curl命令会更有益,因为它需要request.post模仿。
  • 我更新了代码,POST没有实现,只有GET和PUT。我也在发送请求之前打开文件,看看里面有什么,同样的问题。使用 curl 我只使用 curl "http://monitoringtest.local.domain/test/check_mk/webapi.py?action=set_hosttags&_username=user&_secret=secret" -d 'request{data content}"
  • 我试图用json.dumps(data['result'])) 强制 json 没有任何成功

标签: python-3.x python-requests check-mk


【解决方案1】:

我发现了错误,只是注意力不集中。 Data 变量包含两个键,它们在开头发送result,在结尾发送result_code,需要截断。我只需要修改响应如下,并通过 POST 发送数据:

resp = requests.post(url, params=params_set, data={'request': json.dumps(data['result'])})

感谢@DeepSpace

【讨论】:

    猜你喜欢
    • 2016-02-04
    • 2022-08-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 2018-10-02
    相关资源
    最近更新 更多