I've been using Python to access the Rdio API a fair bit so decided to add a couple methods to the Rdio module to make life easier. I keep getting stymied.
Here, as background, is some of the Rdio Python module provided by the company:
class Rdio:
def __init__(self, consumer, token=None):
self.__consumer = consumer
self.token = token
def __signed_post(self, url, params):
auth = om(self.__consumer, url, params, self.token)
req = urllib2.Request(url, urllib.urlencode(params), {'Authorization': auth})
res = urllib2.urlopen(req)
return res.read()
def call(self, method, params=dict()):
# make a copy of the dict
params = dict(params)
# put the method in the dict
params['method'] = method
# call to the server and parse the response
return json.loads(self.__signed_post('http://api.rdio.com/1/', params))
Okay, all well and good. Those functions work fine. So I decided to create a method that would copy a playlist with key1
into a playlist with key2
. Here's the code:
def copy_playlist(self, key1, key2):
#get track keys from first playlist
playlist = self.call('get', {'keys': key1, 'extras' : 'tracks'})
track_keys = []
for track in tracks:
key = track['key']
track_keys.append(key)
#convert track list into single, comma-separated string (which the API requires)
keys_string = ', '.join(track_keys)
#add the tracks to the second playlist
self.call('addToPlaylist', {'playlist' : key2, 'tracks' : keys_string})
This code works fine if I do it from the terminal or in an external Python file, but for some reason when I include it as part of the Rdio class, then initiate the Rdio object as rdio
and call the playlist method, I always get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "rdio_extended.py", line 83, in copy_playlist
NameError: global name 'rdio' is not defined
I can't seem to get around this. There's probably a simple answer - I'm pretty new to programming - but I'm stumped.
UPDATE: Updated code formatting, and here's the actual code that creates the Rdio object:
rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET), (RDIO_TOKEN, RDIO_TOKEN_SECRET))
And then this is the line to call the playlist-copying function:
rdio.copy_playlist(key1, key2)
That results in the NameError described above.