代码之家  ›  专栏  ›  技术社区  ›  Hackerds

python请求库:从附加路径获取响应的函数

  •  1
  • Hackerds  · 技术社区  · 6 年前

    我想在Thingworx平台上得到一个东西的价值。我有下面的代码来实现这个结果。

    import json
    import requests
    url = 'https://academic.cloud.thingworx.com/Thingworx/Things/weatherrover1/Properties/battery'
    
    headers = {'appKey': 'fdb123fc-e369-483b-baa5-8445bd8746ee',
               'Accept': 'application/json'}
    
    getreq = requests.get(url, headers=headers)
    

    但我试着把URL分解成基本URL,直到 'https://academic.cloud.thingworx.com/' 然后定义变量来获得响应。但是失败了。下面是我试过的代码。

    import json
    import requests
    
    url = 'https://academic.cloud.thingworx.com/'
    params = { 'Platform': 'Thingworx',
               'Things': 'Things',
               'Entity':'Things',
               'Thing_Name':'weatherrover1',
               'Properties':'Properties',
               'Property_Name':'battery'}
    
    getreq = requests.get(url, params = params, headers=headers)
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   Martijn Pieters    6 年前

    这个 params 论点是 为了定义查询参数,在 ? 在URL中。

    你添加了 给你的 ,这无法获得所需的URL,因为URL路径是 之前 这个 在URL中。你可以用 string formatting 以扩展路径。

    字符串格式可以使用模板,因此URL可以是:

    url_template = 'https://academic.cloud.thingworx.com/{platform}/{entity}/{entity_name}/Properties/{property}'
    

    {...} 占位符名称可以从字典中获取:

    url_parts = {
        'entity': 'Things',
        'platform': 'Thingworx',
        'entity': 'Things',
        'entity_name': 'weatherrover1',
        'property': 'battery'
    }
    
    url_template.format(**url_parts)
    

    url_template.format(**url_parts) 导致 requests.get()

    response = requests.get(url_template.format(**url_parts), headers=headers)