Skip to content

Commit

Permalink
Improved stability by usinf Python f-string as much as possible to pr…
Browse files Browse the repository at this point in the history
…event TypeError and improve code readability.
  • Loading branch information
morpheus65535 committed Oct 18, 2023
1 parent 4521b11 commit 2ad7ddf
Show file tree
Hide file tree
Showing 52 changed files with 284 additions and 294 deletions.
2 changes: 1 addition & 1 deletion bazarr/api/episodes/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def get(self):
del item['external_subtitles']

if item['score']:
item['score'] = str(round((int(item['score']) * 100 / 360), 2)) + "%"
item['score'] = f"{round((int(item['score']) * 100 / 360), 2)}%"

# Make timestamp pretty
if item['timestamp']:
Expand Down
2 changes: 1 addition & 1 deletion bazarr/api/movies/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def get(self):
del item['external_subtitles']

if item['score']:
item['score'] = str(round((int(item['score']) * 100 / 120), 2)) + "%"
item['score'] = f"{round((int(item['score']) * 100 / 120), 2)}%"

# Make timestamp pretty
if item['timestamp']:
Expand Down
3 changes: 2 additions & 1 deletion bazarr/api/system/releases.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,6 @@ def get(self):

except Exception:
logging.exception(
'BAZARR cannot parse releases caching file: ' + os.path.join(args.config_dir, 'config', 'releases.txt'))
f'BAZARR cannot parse releases caching file: '
f'{os.path.join(args.config_dir, "config", "releases.txt")}')
return marshal(filtered_releases, self.get_response_model, envelope='data')
2 changes: 1 addition & 1 deletion bazarr/api/webhooks/plex.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def post(self):
if media_type == 'episode':
try:
episode_imdb_id = [x['imdb'] for x in ids if 'imdb' in x][0]
r = requests.get('https://imdb.com/title/{}'.format(episode_imdb_id),
r = requests.get(f'https://imdb.com/title/{episode_imdb_id}',
headers={"User-Agent": os.environ["SZ_USER_AGENT"]})
soup = bso(r.content, "html.parser")
script_tag = soup.find(id='__NEXT_DATA__')
Expand Down
2 changes: 1 addition & 1 deletion bazarr/app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def create_app():
else:
app.config["DEBUG"] = False

socketio.init_app(app, path=base_url.rstrip('/')+'/api/socket.io', cors_allowed_origins='*',
socketio.init_app(app, path=f'{base_url.rstrip("/")}/api/socket.io', cors_allowed_origins='*',
async_mode='threading', allow_upgrades=False, transports='polling')

@app.errorhandler(404)
Expand Down
66 changes: 33 additions & 33 deletions bazarr/app/check_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def check_releases():
releases = []
url_releases = 'https://api.github.com/repos/morpheus65535/Bazarr/releases?per_page=100'
try:
logging.debug('BAZARR getting releases from Github: {}'.format(url_releases))
logging.debug(f'BAZARR getting releases from Github: {url_releases}')
r = requests.get(url_releases, allow_redirects=True)
r.raise_for_status()
except requests.exceptions.HTTPError:
Expand All @@ -50,7 +50,7 @@ def check_releases():
'download_link': download_link})
with open(os.path.join(args.config_dir, 'config', 'releases.txt'), 'w') as f:
json.dump(releases, f)
logging.debug('BAZARR saved {} releases to releases.txt'.format(len(r.json())))
logging.debug(f'BAZARR saved {len(r.json())} releases to releases.txt')


def check_if_new_update():
Expand All @@ -59,9 +59,9 @@ def check_if_new_update():
elif settings.general.branch == 'development':
use_prerelease = True
else:
logging.error('BAZARR unknown branch provided to updater: {}'.format(settings.general.branch))
logging.error(f'BAZARR unknown branch provided to updater: {settings.general.branch}')
return
logging.debug('BAZARR updater is using {} branch'.format(settings.general.branch))
logging.debug(f'BAZARR updater is using {settings.general.branch} branch')

check_releases()

Expand All @@ -84,7 +84,7 @@ def check_if_new_update():
release = next((item for item in data if not item["prerelease"]), None)

if release and 'name' in release:
logging.debug('BAZARR last release available is {}'.format(release['name']))
logging.debug(f'BAZARR last release available is {release["name"]}')
if deprecated_python_version():
logging.warning('BAZARR is using a deprecated Python version, you must update Python to get latest '
'version available.')
Expand All @@ -101,12 +101,12 @@ def check_if_new_update():

# skip update process if latest release is v0.9.1.1 which is the latest pre-semver compatible release
if new_version and release['name'] != 'v0.9.1.1':
logging.debug('BAZARR newer release available and will be downloaded: {}'.format(release['name']))
logging.debug(f'BAZARR newer release available and will be downloaded: {release["name"]}')
download_release(url=release['download_link'])
# rolling back from nightly to stable release
elif current_version:
if current_version.prerelease and not use_prerelease:
logging.debug('BAZARR previous stable version will be downloaded: {}'.format(release['name']))
logging.debug(f'BAZARR previous stable version will be downloaded: {release["name"]}')
download_release(url=release['download_link'])
else:
logging.debug('BAZARR no newer release have been found')
Expand All @@ -122,9 +122,9 @@ def download_release(url):
try:
os.makedirs(update_dir, exist_ok=True)
except Exception:
logging.debug('BAZARR unable to create update directory {}'.format(update_dir))
logging.debug(f'BAZARR unable to create update directory {update_dir}')
else:
logging.debug('BAZARR downloading release from Github: {}'.format(url))
logging.debug(f'BAZARR downloading release from Github: {url}')
r = requests.get(url, allow_redirects=True)
if r:
try:
Expand All @@ -145,7 +145,7 @@ def apply_update():

if os.path.isdir(update_dir):
if os.path.isfile(bazarr_zip):
logging.debug('BAZARR is trying to unzip this release to {0}: {1}'.format(bazarr_dir, bazarr_zip))
logging.debug(f'BAZARR is trying to unzip this release to {bazarr_dir}: {bazarr_zip}')
try:
with ZipFile(bazarr_zip, 'r') as archive:
zip_root_directory = ''
Expand Down Expand Up @@ -195,7 +195,7 @@ def apply_update():
def update_cleaner(zipfile, bazarr_dir, config_dir):
with ZipFile(zipfile, 'r') as archive:
file_in_zip = archive.namelist()
logging.debug('BAZARR zip file contain {} directories and files'.format(len(file_in_zip)))
logging.debug(f'BAZARR zip file contain {len(file_in_zip)} directories and files')
separator = os.path.sep
if os.path.sep == '\\':
logging.debug('BAZARR upgrade leftover cleaner is running on Windows. We\'ll fix the zip file separator '
Expand All @@ -207,33 +207,33 @@ def update_cleaner(zipfile, bazarr_dir, config_dir):
logging.debug('BAZARR upgrade leftover cleaner is running on something else than Windows. The zip file '
'separator are fine.')

dir_to_ignore = ['^.' + separator,
'^bin' + separator,
'^venv' + separator,
'^WinPython' + separator,
separator + '__pycache__' + separator + '$']
dir_to_ignore = [f'^.{separator}',
f'^bin{separator}',
f'^venv{separator}',
f'^WinPython{separator}',
f'{separator}__pycache__{separator}$']
if os.path.abspath(bazarr_dir).lower() == os.path.abspath(config_dir).lower():
# for users who installed Bazarr inside the config directory (ie: `%programdata%\Bazarr` on windows)
dir_to_ignore.append('^backup' + separator)
dir_to_ignore.append('^cache' + separator)
dir_to_ignore.append('^config' + separator)
dir_to_ignore.append('^db' + separator)
dir_to_ignore.append('^log' + separator)
dir_to_ignore.append('^restore' + separator)
dir_to_ignore.append('^update' + separator)
dir_to_ignore.append(f'^backup{separator}')
dir_to_ignore.append(f'^cache{separator}')
dir_to_ignore.append(f'^config{separator}')
dir_to_ignore.append(f'^db{separator}')
dir_to_ignore.append(f'^log{separator}')
dir_to_ignore.append(f'^restore{separator}')
dir_to_ignore.append(f'^update{separator}')
elif os.path.abspath(bazarr_dir).lower() in os.path.abspath(config_dir).lower():
# when config directory is a child of Bazarr installation directory
dir_to_ignore.append('^' + os.path.relpath(config_dir, bazarr_dir) + separator)
dir_to_ignore.append(f'^{os.path.relpath(config_dir, bazarr_dir)}{separator}')
dir_to_ignore_regex_string = '(?:% s)' % '|'.join(dir_to_ignore)
logging.debug(f'BAZARR upgrade leftover cleaner will ignore directories matching this '
f'regex: {dir_to_ignore_regex_string}')
dir_to_ignore_regex = re.compile(dir_to_ignore_regex_string)

file_to_ignore = ['nssm.exe', '7za.exe', 'unins000.exe', 'unins000.dat']
logging.debug('BAZARR upgrade leftover cleaner will ignore those files: {}'.format(', '.join(file_to_ignore)))
logging.debug(f'BAZARR upgrade leftover cleaner will ignore those files: {", ".join(file_to_ignore)}')
extension_to_ignore = ['.pyc']
logging.debug('BAZARR upgrade leftover cleaner will ignore files with those extensions: '
'{}'.format(', '.join(extension_to_ignore)))
logging.debug(
f'BAZARR upgrade leftover cleaner will ignore files with those extensions: {", ".join(extension_to_ignore)}')

file_on_disk = []
folder_list = []
Expand All @@ -256,14 +256,14 @@ def update_cleaner(zipfile, bazarr_dir, config_dir):
filepath = os.path.join(current_dir, file)
if not dir_to_ignore_regex.findall(filepath):
file_on_disk.append(filepath)
logging.debug('BAZARR directory contain {} files'.format(len(file_on_disk)))
logging.debug('BAZARR directory contain {} directories'.format(len(folder_list)))
logging.debug(f'BAZARR directory contain {len(file_on_disk)} files')
logging.debug(f'BAZARR directory contain {len(folder_list)} directories')
file_on_disk += folder_list
logging.debug('BAZARR directory contain {} directories and files'.format(len(file_on_disk)))
logging.debug(f'BAZARR directory contain {len(file_on_disk)} directories and files')

file_to_remove = list(set(file_on_disk) - set(file_in_zip))
logging.debug('BAZARR will delete {} directories and files'.format(len(file_to_remove)))
logging.debug('BAZARR will delete this: {}'.format(', '.join(file_to_remove)))
logging.debug(f'BAZARR will delete {len(file_to_remove)} directories and files')
logging.debug(f'BAZARR will delete this: {", ".join(file_to_remove)}')

for file in file_to_remove:
filepath = os.path.join(bazarr_dir, file)
Expand All @@ -273,4 +273,4 @@ def update_cleaner(zipfile, bazarr_dir, config_dir):
else:
os.remove(filepath)
except Exception:
logging.debug('BAZARR upgrade leftover cleaner cannot delete {}'.format(filepath))
logging.debug(f'BAZARR upgrade leftover cleaner cannot delete {filepath}')
8 changes: 4 additions & 4 deletions bazarr/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ def convert_ini_to_yaml(config_file):
output_dict[section].update({item[0]: item[1]})
with open(os.path.join(os.path.dirname(config_file), 'config.yaml'), 'w') as file:
yaml.dump(output_dict, file)
os.rename(config_file, config_file + '.old')
os.rename(config_file, f'{config_file}.old')


config_yaml_file = os.path.join(args.config_dir, 'config', 'config.yaml')
Expand Down Expand Up @@ -761,10 +761,10 @@ def configure_captcha_func():
def configure_proxy_func():
if settings.proxy.type:
if settings.proxy.username != '' and settings.proxy.password != '':
proxy = settings.proxy.type + '://' + quote_plus(settings.proxy.username) + ':' + \
quote_plus(settings.proxy.password) + '@' + settings.proxy.url + ':' + str(settings.proxy.port)
proxy = (f'{settings.proxy.type}://{quote_plus(settings.proxy.username)}:'
f'{quote_plus(settings.proxy.password)}@{settings.proxy.url}:{settings.proxy.port}')
else:
proxy = settings.proxy.type + '://' + settings.proxy.url + ':' + str(settings.proxy.port)
proxy = f'{settings.proxy.type}://{settings.proxy.url}:{settings.proxy.port}'
os.environ['HTTP_PROXY'] = str(proxy)
os.environ['HTTPS_PROXY'] = str(proxy)
exclude = ','.join(settings.proxy.exclude)
Expand Down
4 changes: 2 additions & 2 deletions bazarr/app/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,11 +330,11 @@ def get_exclusion_clause(exclusion_type):
if exclusion_type == 'series':
tagsList = settings.sonarr.excluded_tags
for tag in tagsList:
where_clause.append(~(TableShows.tags.contains("\'" + tag + "\'")))
where_clause.append(~(TableShows.tags.contains(f"\'{tag}\'")))
else:
tagsList = settings.radarr.excluded_tags
for tag in tagsList:
where_clause.append(~(TableMovies.tags.contains("\'" + tag + "\'")))
where_clause.append(~(TableMovies.tags.contains(f"\'{tag}\'")))

if exclusion_type == 'series':
monitoredOnly = settings.sonarr.only_monitored
Expand Down
2 changes: 1 addition & 1 deletion bazarr/app/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ def getFilesToDelete(self):
result = []
# See bpo-44753: Don't use the extension when computing the prefix.
n, e = os.path.splitext(baseName)
prefix = n + '.'
prefix = f'{n}.'
plen = len(prefix)
for fileName in fileNames:
if self.namer is None:
Expand Down
11 changes: 5 additions & 6 deletions bazarr/app/notifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def update_notifier():
for x in results['schemas']:
if x['service_name'] not in notifiers_in_db:
notifiers_added.append({'name': str(x['service_name']), 'enabled': 0})
logging.debug('Adding new notifier agent: ' + str(x['service_name']))
logging.debug(f'Adding new notifier agent: {x["service_name"]}')
else:
notifiers_kept.append(x['service_name'])

Expand Down Expand Up @@ -60,7 +60,7 @@ def send_notifications(sonarr_series_id, sonarr_episode_id, message):
series_title = series.title
series_year = series.year
if series_year not in [None, '', '0']:
series_year = ' ({})'.format(series_year)
series_year = f' ({series_year})'
else:
series_year = ''
episode = database.execute(
Expand All @@ -80,8 +80,7 @@ def send_notifications(sonarr_series_id, sonarr_episode_id, message):

apobj.notify(
title='Bazarr notification',
body="{}{} - S{:02d}E{:02d} - {} : {}".format(series_title, series_year, episode.season, episode.episode,
episode.title, message),
body=f"{series_title}{series_year} - S{episode.season:02d}E{episode.episode:02d} - {episode.title} : {message}",
)


Expand All @@ -98,7 +97,7 @@ def send_notifications_movie(radarr_id, message):
movie_title = movie.title
movie_year = movie.year
if movie_year not in [None, '', '0']:
movie_year = ' ({})'.format(movie_year)
movie_year = f' ({movie_year})'
else:
movie_year = ''

Expand All @@ -112,5 +111,5 @@ def send_notifications_movie(radarr_id, message):

apobj.notify(
title='Bazarr notification',
body="{}{} : {}".format(movie_title, movie_year, message),
body=f"{movie_title}{movie_year} : {message}",
)
6 changes: 3 additions & 3 deletions bazarr/app/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,10 @@ def get_time_from_cron(cron):
if day == "*":
text = "everyday"
else:
text = "every " + day_name[int(day)]
text = f"every {day_name[int(day)]}"

if hour != "*":
text += " at " + hour + ":00"
text += f" at {hour}:00"

return text

Expand All @@ -149,7 +149,7 @@ def get_time_from_cron(cron):
running = False

if isinstance(job.trigger, IntervalTrigger):
interval = "every " + get_time_from_interval(job.trigger.__getstate__()['interval'])
interval = f"every {get_time_from_interval(job.trigger.__getstate__()['interval'])}"
task_list.append({'name': job.name, 'interval': interval, 'next_run_in': next_run,
'next_run_time': next_run, 'job_id': job.id, 'job_running': running})
elif isinstance(job.trigger, CronTrigger):
Expand Down
8 changes: 4 additions & 4 deletions bazarr/app/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,13 @@ def shutdown(self):
try:
self.server.close()
except Exception as e:
logging.error('BAZARR Cannot stop Waitress: ' + repr(e))
logging.error(f'BAZARR Cannot stop Waitress: {repr(e)}')
else:
database.close()
try:
stop_file = io.open(os.path.join(args.config_dir, "bazarr.stop"), "w", encoding='UTF-8')
except Exception as e:
logging.error('BAZARR Cannot create stop file: ' + repr(e))
logging.error(f'BAZARR Cannot create stop file: {repr(e)}')
else:
logging.info('Bazarr is being shutdown...')
stop_file.write(str(''))
Expand All @@ -94,13 +94,13 @@ def restart(self):
try:
self.server.close()
except Exception as e:
logging.error('BAZARR Cannot stop Waitress: ' + repr(e))
logging.error(f'BAZARR Cannot stop Waitress: {repr(e)}')
else:
database.close()
try:
restart_file = io.open(os.path.join(args.config_dir, "bazarr.restart"), "w", encoding='UTF-8')
except Exception as e:
logging.error('BAZARR Cannot create restart file: ' + repr(e))
logging.error(f'BAZARR Cannot create restart file: {repr(e)}')
else:
logging.info('Bazarr is being restarted...')
restart_file.write(str(''))
Expand Down
Loading

0 comments on commit 2ad7ddf

Please sign in to comment.