在python中为Hue灯添加变量到URL

时间:2017-04-07 04:43:39

标签: python rest put philips-hue

我知道你可以使用变量缩短这个python api调用hue的长度,但是我无法弄清楚在stackoverflow中找到答案的格式或正确的术语。我想学习如何隐藏身份验证令以实现更好的安全性,并为将来可能添加的多个灯添加变量。我相信我需要URL中的多个变量。如有任何帮助,将不胜感激。

import requests

url = "http://192.168.98.233/api/Cjk7782cABRgUggxUTlt8DwwnK516ilhMHzHwFlq/lights/{}/state".format(1)
url2= "http://192.168.98.233/api/Cjk7782cABRgUggxUTlt8DwwnK516ilhMHzHwFlq/lights/{}/state".format(2)
url3= "http://192.168.98.233/api/Cjk7782cABRgUggxUTlt8DwwnK516ilhMHzHwFlq/lights/{}/state".format(3)

payload = " {\"on\":false}"
headers = {
    'content-type': "application/json",
    'cache-control': "no-cache"
    }

r = requests.put(url, data=payload, headers=headers)
r2 = requests.put(url2, data=payload, headers=headers)
r3 = requests.put(url3, data=payload, headers=headers)
print(r.text)
print(r2.text)
print(r3.text)

1 个答案:

答案 0 :(得分:1)

像这样:

import requests

payload = " {\"on\":false}"
headers = {
    'content-type': "application/json",
    'cache-control': "no-cache"
}

for i in range(1, 4) : 
    url = "http://192.168.98.233/api/Cjk7782cABRgUggxUTlt8DwwnK516ilhMHzHwFlq/lights/{}/state".format(i)
    r = requests.put(url, data=payload, headers=headers)
    print(r.text)