From 61ddaa0f6ea3ca1bac1543be4a382928076ffea4 Mon Sep 17 00:00:00 2001 From: Amaury Medeiros Date: Fri, 13 Jun 2014 17:49:55 -0300 Subject: [PATCH] Change the code to let it more pythonic. --- examples/try_new_things.py | 36 +++++++++++++++---------------- pyechonest/util.py | 44 +++++++++++++++++++------------------- 2 files changed, 40 insertions(+), 40 deletions(-) diff --git a/examples/try_new_things.py b/examples/try_new_things.py index 827ac2c..a5bd99a 100755 --- a/examples/try_new_things.py +++ b/examples/try_new_things.py @@ -20,8 +20,8 @@ # = try_new_things.py = # ======================== # -# enter a few of your favorite artists and create a playlist of new music that -# you might like. +# enter a few of your favorite artists and create a playlist of new music that +# you might like. # import sys, os, logging @@ -41,28 +41,28 @@ def __init__(self, outStream, indentAmount=' '): self._out = outStream self._indentAmount = indentAmount self._stack = [ ] - + def prolog(self, encoding='UTF-8', version='1.0'): pi = '' % (version, encoding) self._out.write(pi + '\n') - + def start(self, name, attrs={ }): indent = self._getIndention() self._stack.append(name) self._out.write(indent + self._makeTag(name, attrs) + '\n') - + def end(self): name = self._stack.pop() indent = self._getIndention() self._out.write('%s\n' % (indent, name)) - + def elem(self, name, value, attrs={ }): # delete attributes with an unset value for (k, v) in attrs.items(): - if v is None or v == '': + if not v: del attrs[k] - - if value is None or value == '': + + if not value: if len(attrs) == 0: return self._out.write(self._getIndention()) @@ -73,25 +73,25 @@ def elem(self, name, value, attrs={ }): self._out.write(self._makeTag(name, attrs)) self._out.write(escValue) self._out.write('\n' % name) - + def _getIndention(self): return self._indentAmount * len(self._stack) - + def _makeTag(self, name, attrs={ }, close=False): ret = '<' + name - + for (k, v) in attrs.iteritems(): if v is not None: v = saxutils.quoteattr(str(v)) ret += ' %s=%s' % (k, v) - + if close: return ret + '/>' else: return ret + '>' - - + + def write_xspf(f, tuples): """send me a list of (artist,title,mp3_url)""" xml = XmlWriter(f, indentAmount=' ') @@ -138,7 +138,7 @@ def find_playlist(seed_artist_ids, playable=False): 'example:\n' \ '\t ./%prog "arcade fire" "feist" "broken social scene" -x -f arcade_feist_scene.xspf\n' \ '\t ./%prog "justice" "four tet" "bitshifter" -v\n' - + parser = OptionParser(usage=usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, @@ -162,7 +162,7 @@ def find_playlist(seed_artist_ids, playable=False): log_level = logging.INFO logging.basicConfig(level=log_level) logger.setLevel(log_level) - + # make sure output file doesn't already exist if options.filename and os.path.exists(options.filename): logger.error("The file path: %s already exists." % (options.filename,)) @@ -173,7 +173,7 @@ def find_playlist(seed_artist_ids, playable=False): # find playlist raw_plist = find_playlist(seed_ids, playable=(options.audio or options.xspf)) - + tuple_plist = [] for s in raw_plist: name = s.artist_name diff --git a/pyechonest/util.py b/pyechonest/util.py index 88b9e0f..8c07019 100644 --- a/pyechonest/util.py +++ b/pyechonest/util.py @@ -49,7 +49,7 @@ def default_open(self, request): logger.info("%s" % (request.get_full_url(),)) request.start_time = time.time() return None - + class MyErrorProcessor(urllib2.HTTPErrorProcessor): def http_response(self, request, response): code = response.code @@ -159,12 +159,12 @@ def codegen(filename, start=0, duration=30): if not os.path.exists(cmd): raise Exception("Codegen binary not found.") - command = cmd + " \"" + filename + "\" " + command = cmd + " \"" + filename + "\" " if start >= 0: command = command + str(start) + " " if duration >= 0: command = command + str(duration) - + p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (json_block, errs) = p.communicate() json_block = reallyUTF8(json_block) @@ -178,10 +178,10 @@ def codegen(filename, start=0, duration=30): def callm(method, param_dict, POST=False, socket_timeout=None, data=None): """ - Call the api! + Call the api! Param_dict is a *regular* *python* *dictionary* so if you want to have multi-valued params put them in a list. - + ** note, if we require 2.6, we can get rid of this timeout munging. """ try: @@ -267,10 +267,10 @@ def oauthgetm(method, param_dict, socket_timeout=None): raise Exception("You must install the python-oauth2 library to use this method.") """ - Call the api! With Oauth! + Call the api! With Oauth! Param_dict is a *regular* *python* *dictionary* so if you want to have multi-valued params put them in a list. - + ** note, if we require 2.6, we can get rid of this timeout munging. """ def build_request(url): @@ -281,17 +281,17 @@ def build_request(url): } consumer = oauth2.Consumer(key=config.ECHO_NEST_CONSUMER_KEY, secret=config.ECHO_NEST_SHARED_SECRET) params['oauth_consumer_key'] = config.ECHO_NEST_CONSUMER_KEY - + req = oauth2.Request(method='GET', url=url, parameters=params) signature_method = oauth2.SignatureMethod_HMAC_SHA1() req.sign_request(signature_method, consumer, None) return req - + param_dict['api_key'] = config.ECHO_NEST_API_KEY param_list = [] if not socket_timeout: socket_timeout = config.CALL_TIMEOUT - + for key,val in param_dict.iteritems(): if isinstance(val, list): param_list.extend( [(key,subval) for subval in val] ) @@ -301,19 +301,19 @@ def build_request(url): param_list.append( (key,val) ) params = urllib.urlencode(param_list) - + orig_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(socket_timeout) """ just a normal GET call """ - url = 'http://%s/%s/%s/%s?%s' % (config.API_HOST, config.API_SELECTOR, config.API_VERSION, + url = 'http://%s/%s/%s/%s?%s' % (config.API_HOST, config.API_SELECTOR, config.API_VERSION, method, params) req = build_request(url) f = opener.open(req.to_url()) - + socket.setdefaulttimeout(orig_timeout) - + # try/except response_dict = get_successful_response(f) return response_dict @@ -323,14 +323,14 @@ def postChunked(host, selector, fields, files): """ Attempt to replace postMultipart() with nearly-identical interface. (The files tuple no longer requires the filename, and we only return - the response body.) - Uses the urllib2_file.py originally from - http://fabien.seisen.org which was also drawn heavily from + the response body.) + Uses the urllib2_file.py originally from + http://fabien.seisen.org which was also drawn heavily from http://code.activestate.com/recipes/146306/ . - - This urllib2_file.py is more desirable because of the chunked - uploading from a file pointer (no need to read entire file into - memory) and the ability to work from behind a proxy (due to its + + This urllib2_file.py is more desirable because of the chunked + uploading from a file pointer (no need to read entire file into + memory) and the ability to work from behind a proxy (due to its basis on urllib2). """ params = urllib.urlencode(fields) @@ -348,6 +348,6 @@ def fix(x): def map_idspace(input_idspace): - if input_idspace == 'spotify-WW' or input_idspace == 'spotifyv2-ZZ': + if input_idspace in ['spotify-WW', 'spotifyv2-ZZ']: return 'spotify' return input_idspace