我在互联网上搜索(以及stackoverflow :D),找出以下问题的答案--但我发现没有一个理解。
背景:
我们希望使用python脚本将我们的公司CMDB与AWX/Ansible基础设施连接起来。
CMDB有一个REST ,它支持(一半)正确的导出。
我目前正忙于实现正确的API调用。
我可以调用API本身并进行身份验证,但不能调用适当的过滤器来获得所需的结果。
过滤器是通过在URL中包含以下字符串来实现的(在附加的代码示例中有更多信息)
Label LIKE "host*"似乎python与*有问题。
错误信息:
InvalidURL(f"URL can't contain control characters. {url!r} "我发现了一些bug报告,在某些python版本中存在问题,但我想了解一下这是否会影响到这里的情况:D
用python版本3.7.4
PS:让我们看看我能不能把标记弄对:D
我切换了被调用的URL,以确定问题的确切位置。
只有当我使用类似SQL的筛选器部分时,才会发生这种情况。
这个部分非常重要,因为我只想返回我们的“主机”,而不是整个CMDB本身。
#import the required classes and such
from http.client import HTTPConnection
import json#create a HTTP connection client
client = HTTPConnection("cmdb.example.company")#basic auth and some header details
headers = {'Content-Type': 'application/json',
'Authorization' : 'Basic my-auth-token'}#working API call
client.request('GET', '/cmdb/rest/hosts?attributes=Label,Keywords,Tag,Description&limit=10', headers=headers)
#broken API call returns - InvalidURL(f"URL can't contain control characters. {url!r} "
client.request('GET', '/cmdb/rest/hosts?filter=Label LIKE "host*"&attributes=Label,Keywords,Tag,Description&limit=10', headers=headers)#check and convert the response into a readable (JSON) format
response = client.getresponse()
data = response.read()
#debugging print - show that the returned data is bytes?!
print(data)
#convert the returned data into json
my_json = data.decode('utf8').replace("'", '"')
data = json.loads(my_json)
#only return the data part from the JSON and ignore the meta-overhead
text = json.dumps(data["data"], sort_keys=True, indent=4)
print(text)因此,我想知道如何使用描述的过滤器正确地调用API并解决显示的错误。
你能给我举个例子吗?我能试一下初学者犯的错误吗?
我是否受到了关于包含*的URL调用的python错误的影响?
(谢谢你帮我:)
发布于 2019-09-27 08:48:33
所以我发现我的初学者自己弄错了:
我使用了来自浏览器的URL,我的浏览器自动对URL中的特殊字符进行编码。
我在Python3 URL中找到了编码指南的代码,并修改了字符串以满足我的需要:)
import urllib.parse
query = ' "host*"'
urllib.parse.quote(query)
'%20%22host%2A%22'结果:‘%20%22宿主%2A%22’‘
%20 =“”
%22 =“”
%2A = "*“
所以最后的代码看起来有点像这样:
#broken API call returns - InvalidURL(f"URL can't contain control characters. {url!r} "
client.request('GET', '/cmdb/rest/hosts?filter=Label LIKE "host*"&attributes=Label,Keywords,Tag,Description&limit=10', headers=headers)filter=Label喜欢“主机*”
#fixed API call
client.request('GET', '/cmdb/rest/hosts?filter=Label%20LIKE%20%22host%2A%22&attributes=Label,Keywords,Tag,Description&limit=10', headers=headers)filter=Label%20LIKE%20%22host%2A%22
https://stackoverflow.com/questions/58081605
复制相似问题