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
+6 -23
View File
@@ -13,29 +13,12 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Headphones. If not, see <http://www.gnu.org/licenses/>. # 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): class HeadphonesException(Exception):
"Generic Headphones Exception - should never be thrown, only subclassed" """
Generic Headphones Exception - should never be thrown, only subclassed
"""
class NewzbinAPIThrottled(HeadphonesException): class NewzbinAPIThrottled(HeadphonesException):
"Newzbin has throttled us, deal with it" """
Newzbin has throttled us, deal with it
"""
+5 -3
View File
@@ -603,9 +603,11 @@ def create_https_certificates(ssl_cert, ssl_key):
# Save the key and certificate to disk # Save the key and certificate to disk
try: try:
open(ssl_key, 'w').write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) with open(ssl_key, 'w') as f:
open(ssl_cert, 'w').write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
except Exception, e: 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) logger.error("Error creating SSL key and certificate: %s", e)
return False return False
+5 -4
View File
@@ -14,7 +14,6 @@
# along with Headphones. If not, see <http://www.gnu.org/licenses/>. # along with Headphones. If not, see <http://www.gnu.org/licenses/>.
from headphones import logger, helpers, common, request from headphones import logger, helpers, common, request
from headphones.exceptions import ex
from xml.dom import minidom from xml.dom import minidom
from httplib import HTTPSConnection from httplib import HTTPSConnection
@@ -90,7 +89,9 @@ class GROWL:
# Send it, including an image # Send it, including an image
image_file = os.path.join(str(headphones.PROG_DIR), 'data/images/headphoneslogo.png') 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: try:
growl.notify( growl.notify(
@@ -249,8 +250,8 @@ class XBMC:
if not request: if not request:
raise Exception raise Exception
except: except Exception:
logger.warn('Error sending notification request to XBMC') logger.error('Error sending notification request to XBMC')
class LMS: class LMS:
+9 -8
View File
@@ -569,25 +569,27 @@ def addAlbumArt(artwork, albumpath, release):
album_art_name = album_art_name.replace(".", "_", 1) album_art_name = album_art_name.replace(".", "_", 1)
try: try:
file = open(os.path.join(albumpath, album_art_name), 'wb') with open(os.path.join(albumpath, album_art_name), 'wb') as f:
file.write(artwork) f.write(artwork)
file.close() except IOError as e:
except Exception, e: logger.error('Error saving album art: %s', e)
logger.error('Error saving album art: %s' % str(e))
return return
def cleanupFiles(albumpath): def cleanupFiles(albumpath):
logger.info('Cleaning up files') logger.info('Cleaning up files')
for r,d,f in os.walk(albumpath): for r,d,f in os.walk(albumpath):
for files in f: for files in f:
if not any(files.lower().endswith('.' + x.lower()) for x in headphones.MEDIA_FORMATS): if not any(files.lower().endswith('.' + x.lower()) for x in headphones.MEDIA_FORMATS):
logger.debug('Removing: %s' % files) logger.debug('Removing: %s' % files)
try: try:
os.remove(os.path.join(r, files)) 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)) logger.error(u'Could not remove file: %s. Error: %s' % (files.decode(headphones.SYS_ENCODING, 'replace'), e))
def renameNFO(albumpath): def renameNFO(albumpath):
logger.info('Renaming NFO')
for r,d,f in os.walk(albumpath): for r,d,f in os.walk(albumpath):
for file in f: for file in f:
if file.lower().endswith('.nfo'): if file.lower().endswith('.nfo'):
@@ -595,11 +597,10 @@ def renameNFO(albumpath):
try: try:
new_file_name = os.path.join(r, file)[:-3] + 'orig.nfo' new_file_name = os.path.join(r, file)[:-3] + 'orig.nfo'
os.rename(os.path.join(r, file), new_file_name) 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)) 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): def moveFiles(albumpath, release, tracks):
try: try:
year = release['ReleaseDate'][:4] year = release['ReleaseDate'][:4]
except TypeError: except TypeError:
+16 -19
View File
@@ -51,7 +51,7 @@ class Rutracker():
try: try:
self.opener.open("http://login.rutracker.org/forum/login.php", params) self.opener.open("http://login.rutracker.org/forum/login.php", params)
except : except Exception:
pass pass
# Check if we're logged in # Check if we're logged in
@@ -286,17 +286,17 @@ class Rutracker():
else: else:
tempdir = mkdtemp(suffix='_rutracker_torrents') tempdir = mkdtemp(suffix='_rutracker_torrents')
download_path = os.path.join(tempdir, torrent_name) download_path = os.path.join(tempdir, torrent_name)
fp = open (download_path, 'wb')
fp.write (torrent) with open(download_path, 'wb') as f:
fp.close () f.write(torrent)
os.umask(prev) os.umask(prev)
# Add file to utorrent # Add file to utorrent
if headphones.TORRENT_DOWNLOADER == 2: if headphones.TORRENT_DOWNLOADER == 2:
self.utorrent_add_file(download_path) self.utorrent_add_file(download_path)
except Exception, e: except Exception as e:
logger.error('Error getting torrent: %s' % e) logger.error('Error getting torrent: %s', e)
return False return False
return download_path, tor_hash return download_path, tor_hash
@@ -322,9 +322,10 @@ class Rutracker():
try: try:
r = session.get(url + 'token.html') r = session.get(url + 'token.html')
except: except Exception:
logger.debug('Error getting token') logger.exception('Error getting token')
return return
if r.status_code == '401': if r.status_code == '401':
logger.debug('Error reaching utorrent') logger.debug('Error reaching utorrent')
return return
@@ -336,15 +337,11 @@ class Rutracker():
session.params = {'token': regex.group(1)} session.params = {'token': regex.group(1)}
params = {'action': 'add-file'} with open(filename, 'rb') as f:
f = open(filename, 'rb') try:
files = {'torrent_file': f} session.post(url, params={'action': 'add-file'},
files={'torrent_file': f})
try: except Exception:
session.post(url, params=params, files=files) logger.exception('Error adding file to utorrent')
except: return
logger.debug('Error adding file to utorrent')
return
finally:
f.close()
+2 -3
View File
@@ -31,9 +31,8 @@ def addTorrent(link):
method = 'torrent-add' method = 'torrent-add'
if link.endswith('.torrent'): if link.endswith('.torrent'):
f = open(link,'rb') with open(link, 'rb') as f:
metainfo = str(base64.b64encode(f.read())) metainfo = str(base64.b64encode(f.read()))
f.close()
arguments = {'metainfo': metainfo, 'download-dir':headphones.DOWNLOAD_TORRENT_DIR} arguments = {'metainfo': metainfo, 'download-dir':headphones.DOWNLOAD_TORRENT_DIR}
else: else:
arguments = {'filename': link, 'download-dir': headphones.DOWNLOAD_TORRENT_DIR} arguments = {'filename': link, 'download-dir': headphones.DOWNLOAD_TORRENT_DIR}
+9 -13
View File
@@ -21,7 +21,6 @@ import headphones
import subprocess import subprocess
from headphones import logger, version, request from headphones import logger, version, request
from headphones.exceptions import ex
def runGit(args): def runGit(args):
@@ -63,7 +62,6 @@ def runGit(args):
def getVersion(): def getVersion():
if version.HEADPHONES_VERSION.startswith('win32build'): if version.HEADPHONES_VERSION.startswith('win32build'):
headphones.INSTALL_TYPE = 'win' headphones.INSTALL_TYPE = 'win'
# Don't have a way to update exe yet, but don't want to set VERSION to None # 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): if not os.path.isfile(version_file):
return None, 'master' return None, 'master'
fp = open(version_file, 'r') with open(version_file, 'r') as f:
current_version = fp.read().strip(' \n\r') current_version = f.read().strip(' \n\r')
fp.close()
if current_version: if current_version:
return current_version, headphones.GIT_BRANCH return current_version, headphones.GIT_BRANCH
@@ -199,9 +196,8 @@ def update():
tar_download_path = os.path.join(headphones.PROG_DIR, download_name) tar_download_path = os.path.join(headphones.PROG_DIR, download_name)
# Save tar to disk # Save tar to disk
f = open(tar_download_path, 'wb') with open(tar_download_path, 'wb') as f:
f.write(data) f.write(data)
f.close()
# Extract the tar to update folder # Extract the tar to update folder
logger.info('Extracting file: ' + tar_download_path) logger.info('Extracting file: ' + tar_download_path)
@@ -233,9 +229,9 @@ def update():
# Update version.txt # Update version.txt
try: try:
ver_file = open(version_path, 'w') with open(version_path, 'w') as f:
ver_file.write(str(headphones.LATEST_VERSION)) f.write(str(headphones.LATEST_VERSION))
ver_file.close() except IOError as e:
except IOError, e: logger.error("Unable to write current version to version.txt, " \
logger.error("Unable to write current version to version.txt, update not complete: "+ex(e)) "update not complete: ", e)
return return
+1 -1
View File
@@ -114,7 +114,7 @@ def initialize(options=None):
# Prevent time-outs # Prevent time-outs
cherrypy.engine.timeout_monitor.unsubscribe() cherrypy.engine.timeout_monitor.unsubscribe()
cherrypy.tree.mount(WebInterface(), options['http_root'], config = conf) cherrypy.tree.mount(WebInterface(), options['http_root'], config=conf)
try: try:
cherrypy.process.servers.check_port(options['http_host'], options['http_port']) cherrypy.process.servers.check_port(options['http_host'], options['http_port'])