API Python请求库

2024-09-27 23:19:04 发布

您现在位置:Python中文网/ 问答频道 /正文

为了用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)

Tags: import脚本apijsondataresponseparamsrequests
1条回答
网友
1楼 · 发布于 2024-09-27 23:19:04

params不采用嵌套字典结构。您的API本质上是在查询字符串中请求JSON格式的值,但是您没有提供这些值。在

此外,您的示例URL使用小写的参数名,您的字典包含大写参数。在

相反,requests将在使用URL编码编码之前,通过获取每个元素,将params中的任何容器转换为字符串。对于字典来说,这意味着只使用键;实际上,您将生成以下URL:

>>> import requests
>>> parameters = {"Filter": {"deviceClass": {"$like" : "*Controller*"}},
... "Projection": {"tagValues":{"IdStateMap": 1, "stateDevice": 1}}}
>>> prepped = requests.Request('GET', 'http://example.com/', params=parameters).prepare()
>>> prepped.url
'http://example.com/?Filter=deviceClass&Projection=tagValues'

以下内容将生成与示例URL相同的内容:

^{pr2}$

注意,我对键进行了小写,值是字符串。如果需要,可以使用json.dumps()函数从Python字典中生成这些字符串:

import json

filter = {"deviceClass": {"$like": "*Controller*"}}
projection = {"tagValues": {"IdStateMap": 1, "stateDevice": 1}}
parameters = {
    "filter": json.dumps(filter), 
    "projection": json.dumps(projection),
}

演示:

>>> parameters = {
...     "filter": '{"deviceClass": {"$like" : "*Controller*"}}',
...     "projection": '{"tagValues":{"IdStateMap": 1, "stateDevice": 1}}'
... }
>>> prepped = requests.Request('GET', 'http://example.com/', params=parameters).prepare()
>>> prepped.url
'http://example.com/?filter=%7B%22deviceClass%22%3A+%7B%22%24like%22+%3A+%22%2AController%2A%22%7D%7D&projection=%7B%22tagValues%22%3A%7B%22IdStateMap%22%3A+1%2C+%22stateDevice%22%3A+1%7D%7D'
>>> from urllib.parse import urlparse, parse_qsl
>>> parse_qsl(urlparse(prepped.url).query)
[('filter', '{"deviceClass": {"$like" : "*Controller*"}}'), ('projection', '{"tagValues":{"IdStateMap": 1, "stateDevice": 1}}')]

相关问题 更多 >

    热门问题