为了用python编写api脚本,我一直在挖一个越来越深的洞。我不确定是我做错了什么,还是我误解了投影部分的编写方式。在
这是我将提供的信息。。所以我们有两种方法可以通过JSON或socketJS从API获取信息。我将在底部提供的socketjs代码基本上做了相同的事情。。在
出问题的是,它似乎没有正确地处理参数,我得到的只是相同的值,如果我没有添加过滤器或投影。。有人知道我做错了什么吗?我怀疑我没有正确地使用请求库,但是我已经查看过了,并且在文档中似乎没有找到任何与我的特定案例相关的内容。在
工作插座:
{
"address": "service",
"body": {
"action": "getControlers",
"params": {
"filter": {
"deviceClass": {
"$like" : "*mainControllers*"
}
},
"projection": {
"tagValues": {
"IdMap": 1,
"StateDevice": 1
}
},
"limit":1000
}
}
}
在Python外部通过API Rest的等效行:
^{pr2}$我的脚本如下:
import requests
import json
import os
header = {"Authorization": 'access_token *Iputakeyheretomakethingswork*'}
parameters = {"Filter": {"deviceClass": {"$like" : "*Controller*"}},
"Projection": {"tagValues":{"IdStateMap": 1, "stateDevice": 1}}}
response = requests.get("https://urlgoeshere", headers=header, params=parameters)
print(response.status_code)
data = response.json()
with open('data.txt', 'w') as outfile:
json.dump(data, outfile, sort_keys = True, indent = 4,
ensure_ascii = False)
params
不采用嵌套字典结构。您的API本质上是在查询字符串中请求JSON格式的值,但是您没有提供这些值。在此外,您的示例URL使用小写的参数名,您的字典包含大写参数。在
相反,
requests
将在使用URL编码编码之前,通过获取每个元素,将params
中的任何容器转换为字符串。对于字典来说,这意味着只使用键;实际上,您将生成以下URL:以下内容将生成与示例URL相同的内容:
^{pr2}$注意,我对键进行了小写,值是字符串。如果需要,可以使用
json.dumps()
函数从Python字典中生成这些字符串:演示:
相关问题 更多 >
编程相关推荐