LIFX Developer Zone

Crafting an HTTP PUT with Tropo/Python

#1

I’m attempting to use Tropo/Python script to do an HTTP Push to lifx.
Tropo uses Jython and doesn’t natively support importing modules such as 'requests’
Below is an example of a supported HTTP push from Tropo, and example push with ‘requests’, and my attempt at combining the two. Any help would be appreciated.

#An example of a supported method to Push from Tropo
import urllib
import urllib2

url = 'https://api.tropo.com/v1/applications
username = ''
password = ‘’

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)

values = {
“name”:“Python works 2!”,
“voiceUrl”:“http://website.com”,
“messagingUrl”:“http://website2.com”,
“platform”:“scripting”,
“partition”:“staging”
}

data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()

print the_page

#####################################

example push with ‘requests’ (which isn’t supported in Tropo)

import requests
import json

token = “XXX”

headers = {
“Authorization”: “Bearer %s” % token,
}

payload = {
“states”: [
{
“selector” : “id:XXX”,
“hue”: 200,
“brightness”: 0.1
}
],
“defaults”: {
“power”: “on”,
“saturation”: 0,
“duration”: 2.0

}

}

response = requests.put(‘https://api.lifx.com/v1/lights/states’, data=json.dumps(payload), headers=headers)
print(response.content)

############################

My attempt at combining the two

import urllib
import urllib2

url = "https://api.lifx.com/v1/lights/states"
token = “XXX”

payload = {
“states”: [
{
“selector” : “id:XXX”,
“hue”: 200,
“brightness”: 0.1
}
],
“defaults”: {
“power”: “on”,
“saturation”: 0,
“duration”: 2.0

}

}

data = urllib.urlencode(payload)
req = urllib2.Request(url, data)
req.add_header(‘Authorization’, ‘Bearer %s’ % token)
response = urllib2.urlopen(req)

0 Likes