Another batch of improvements:

* Prefer 'with' statements for open
* Catch proper exceptions
* Remove ex() method, there was only one use and we catch thousands of exceptions.
This commit is contained in:
Bas Stottelaar
2014-09-14 23:14:29 +02:00
parent 43efca9d04
commit 8ec1808313
8 changed files with 53 additions and 74 deletions

View File

@@ -13,29 +13,12 @@
# You should have received a copy of the GNU General Public License
# along with Headphones. If not, see <http://www.gnu.org/licenses/>.
def ex(e):
"""
Returns a string from the exception text if it exists.
"""
# sanity check
if not e.args or not e.args[0]:
return ""
e_message = e.args[0]
# if fixStupidEncodings doesn't fix it then maybe it's not a string, in which case we'll try printing it anyway
if not e_message:
try:
e_message = str(e.args[0])
except:
e_message = ""
return e_message
class HeadphonesException(Exception):
"Generic Headphones Exception - should never be thrown, only subclassed"
"""
Generic Headphones Exception - should never be thrown, only subclassed
"""
class NewzbinAPIThrottled(HeadphonesException):
"Newzbin has throttled us, deal with it"
"""
Newzbin has throttled us, deal with it
"""

View File

@@ -603,9 +603,11 @@ def create_https_certificates(ssl_cert, ssl_key):
# Save the key and certificate to disk
try:
open(ssl_key, 'w').write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
open(ssl_cert, 'w').write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
except Exception, e:
with open(ssl_key, 'w') as f:
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
with open(ssl_cert, 'w') as f:
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
except IOError as e:
logger.error("Error creating SSL key and certificate: %s", e)
return False

View File

@@ -14,7 +14,6 @@
# along with Headphones. If not, see <http://www.gnu.org/licenses/>.
from headphones import logger, helpers, common, request
from headphones.exceptions import ex
from xml.dom import minidom
from httplib import HTTPSConnection
@@ -90,7 +89,9 @@ class GROWL:
# Send it, including an image
image_file = os.path.join(str(headphones.PROG_DIR), 'data/images/headphoneslogo.png')
image = open(image_file, 'rb').read()
with open(image_file, 'rb') as f:
image = f.read()
try:
growl.notify(
@@ -249,8 +250,8 @@ class XBMC:
if not request:
raise Exception
except:
logger.warn('Error sending notification request to XBMC')
except Exception:
logger.error('Error sending notification request to XBMC')
class LMS:

View File

@@ -569,25 +569,27 @@ def addAlbumArt(artwork, albumpath, release):
album_art_name = album_art_name.replace(".", "_", 1)
try:
file = open(os.path.join(albumpath, album_art_name), 'wb')
file.write(artwork)
file.close()
except Exception, e:
logger.error('Error saving album art: %s' % str(e))
with open(os.path.join(albumpath, album_art_name), 'wb') as f:
f.write(artwork)
except IOError as e:
logger.error('Error saving album art: %s', e)
return
def cleanupFiles(albumpath):
logger.info('Cleaning up files')
for r,d,f in os.walk(albumpath):
for files in f:
if not any(files.lower().endswith('.' + x.lower()) for x in headphones.MEDIA_FORMATS):
logger.debug('Removing: %s' % files)
try:
os.remove(os.path.join(r, files))
except Exception, e:
except Exception as e:
logger.error(u'Could not remove file: %s. Error: %s' % (files.decode(headphones.SYS_ENCODING, 'replace'), e))
def renameNFO(albumpath):
logger.info('Renaming NFO')
for r,d,f in os.walk(albumpath):
for file in f:
if file.lower().endswith('.nfo'):
@@ -595,11 +597,10 @@ def renameNFO(albumpath):
try:
new_file_name = os.path.join(r, file)[:-3] + 'orig.nfo'
os.rename(os.path.join(r, file), new_file_name)
except Exception, e:
except Exception as e:
logger.error(u'Could not rename file: %s. Error: %s' % (os.path.join(r, file).decode(headphones.SYS_ENCODING, 'replace'), e))
def moveFiles(albumpath, release, tracks):
try:
year = release['ReleaseDate'][:4]
except TypeError:

View File

@@ -51,7 +51,7 @@ class Rutracker():
try:
self.opener.open("http://login.rutracker.org/forum/login.php", params)
except :
except Exception:
pass
# Check if we're logged in
@@ -286,17 +286,17 @@ class Rutracker():
else:
tempdir = mkdtemp(suffix='_rutracker_torrents')
download_path = os.path.join(tempdir, torrent_name)
fp = open (download_path, 'wb')
fp.write (torrent)
fp.close ()
with open(download_path, 'wb') as f:
f.write(torrent)
os.umask(prev)
# Add file to utorrent
if headphones.TORRENT_DOWNLOADER == 2:
self.utorrent_add_file(download_path)
except Exception, e:
logger.error('Error getting torrent: %s' % e)
except Exception as e:
logger.error('Error getting torrent: %s', e)
return False
return download_path, tor_hash
@@ -322,9 +322,10 @@ class Rutracker():
try:
r = session.get(url + 'token.html')
except:
logger.debug('Error getting token')
except Exception:
logger.exception('Error getting token')
return
if r.status_code == '401':
logger.debug('Error reaching utorrent')
return
@@ -336,15 +337,11 @@ class Rutracker():
session.params = {'token': regex.group(1)}
params = {'action': 'add-file'}
f = open(filename, 'rb')
files = {'torrent_file': f}
try:
session.post(url, params=params, files=files)
except:
logger.debug('Error adding file to utorrent')
return
finally:
f.close()
with open(filename, 'rb') as f:
try:
session.post(url, params={'action': 'add-file'},
files={'torrent_file': f})
except Exception:
logger.exception('Error adding file to utorrent')
return

View File

@@ -31,9 +31,8 @@ def addTorrent(link):
method = 'torrent-add'
if link.endswith('.torrent'):
f = open(link,'rb')
metainfo = str(base64.b64encode(f.read()))
f.close()
with open(link, 'rb') as f:
metainfo = str(base64.b64encode(f.read()))
arguments = {'metainfo': metainfo, 'download-dir':headphones.DOWNLOAD_TORRENT_DIR}
else:
arguments = {'filename': link, 'download-dir': headphones.DOWNLOAD_TORRENT_DIR}

View File

@@ -21,7 +21,6 @@ import headphones
import subprocess
from headphones import logger, version, request
from headphones.exceptions import ex
def runGit(args):
@@ -63,7 +62,6 @@ def runGit(args):
def getVersion():
if version.HEADPHONES_VERSION.startswith('win32build'):
headphones.INSTALL_TYPE = 'win'
# Don't have a way to update exe yet, but don't want to set VERSION to None
@@ -109,9 +107,8 @@ def getVersion():
if not os.path.isfile(version_file):
return None, 'master'
fp = open(version_file, 'r')
current_version = fp.read().strip(' \n\r')
fp.close()
with open(version_file, 'r') as f:
current_version = f.read().strip(' \n\r')
if current_version:
return current_version, headphones.GIT_BRANCH
@@ -199,9 +196,8 @@ def update():
tar_download_path = os.path.join(headphones.PROG_DIR, download_name)
# Save tar to disk
f = open(tar_download_path, 'wb')
f.write(data)
f.close()
with open(tar_download_path, 'wb') as f:
f.write(data)
# Extract the tar to update folder
logger.info('Extracting file: ' + tar_download_path)
@@ -233,9 +229,9 @@ def update():
# Update version.txt
try:
ver_file = open(version_path, 'w')
ver_file.write(str(headphones.LATEST_VERSION))
ver_file.close()
except IOError, e:
logger.error("Unable to write current version to version.txt, update not complete: "+ex(e))
with open(version_path, 'w') as f:
f.write(str(headphones.LATEST_VERSION))
except IOError as e:
logger.error("Unable to write current version to version.txt, " \
"update not complete: ", e)
return

View File

@@ -114,7 +114,7 @@ def initialize(options=None):
# Prevent time-outs
cherrypy.engine.timeout_monitor.unsubscribe()
cherrypy.tree.mount(WebInterface(), options['http_root'], config = conf)
cherrypy.tree.mount(WebInterface(), options['http_root'], config=conf)
try:
cherrypy.process.servers.check_port(options['http_host'], options['http_port'])