Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change the code to let it more pythonic. #28

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 18 additions & 18 deletions examples/try_new_things.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 = '<?xml version="%s" encoding="%s"?>' % (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</%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())
Expand All @@ -73,25 +73,25 @@ def elem(self, name, value, attrs={ }):
self._out.write(self._makeTag(name, attrs))
self._out.write(escValue)
self._out.write('</%s>\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=' ')
Expand Down Expand Up @@ -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,
Expand All @@ -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,))
Expand All @@ -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
Expand Down
44 changes: 22 additions & 22 deletions pyechonest/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down Expand Up @@ -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):
Expand All @@ -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] )
Expand All @@ -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
Expand All @@ -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)
Expand All @@ -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