From 4ea80e9810a14ca3617f08a4ae5cfa6b50482e9a Mon Sep 17 00:00:00 2001 From: Ozzieisaacs Date: Sat, 21 May 2022 21:52:59 +0100 Subject: [PATCH] Code cosmetics --- cps/admin.py | 12 +++++++----- cps/babel.py | 2 ++ cps/cache_buster.py | 14 +++++++------- cps/cli.py | 19 ++++++++++--------- cps/config_sql.py | 22 ++++++++++++---------- cps/converter.py | 7 +++---- cps/debug_info.py | 1 + cps/dep_check.py | 2 +- cps/logger.py | 17 +++++++++-------- 9 files changed, 52 insertions(+), 44 deletions(-) diff --git a/cps/admin.py b/cps/admin.py index 22127eb2..3c889643 100755 --- a/cps/admin.py +++ b/cps/admin.py @@ -160,7 +160,7 @@ def shutdown(): return json.dumps(showtext), 400 -# method is available without login and not protected by CSRF to make it easy reachable, is per default switched of +# method is available without login and not protected by CSRF to make it easy reachable, is per default switched off # needed for docker applications, as changes on metadata.db from host are not visible to application @admi.route("/reconnect", methods=['GET']) def reconnect(): @@ -615,7 +615,8 @@ def load_dialogtexts(element_id): elif element_id == "db_submit": texts["main"] = _('Are you sure you want to change Calibre library location?') elif element_id == "admin_refresh_cover_cache": - texts["main"] = _('Calibre-Web will search for updated Covers and update Cover Thumbnails, this may take a while?') + texts["main"] = _('Calibre-Web will search for updated Covers ' + 'and update Cover Thumbnails, this may take a while?') elif element_id == "btnfullsync": texts["main"] = _("Are you sure you want delete Calibre-Web's sync database " "to force a full sync with your Kobo Reader?") @@ -746,6 +747,7 @@ def edit_restriction(res_type, user_id): ub.session_commit("Changed denied columns of user {} to {}".format(usr.name, usr.denied_column_value)) return "" + @admi.route("/ajax/addrestriction/", methods=['POST']) @login_required @admin_required @@ -1084,7 +1086,7 @@ def _configuration_gdrive_helper(to_save): gdrive_secrets['redirect_uris'][0] ) - # always show google drive settings, but in case of error deny support + # always show Google Drive settings, but in case of error deny support new_gdrive_value = (not gdrive_error) and ("config_use_google_drive" in to_save) if config.config_use_google_drive and not new_gdrive_value: config.config_google_drive_watch_changes_response = {} @@ -1837,7 +1839,7 @@ def _handle_new_user(to_save, content, languages, translations, kobo_support): log.info("Missing entries on new user") raise Exception(_(u"Please fill out all fields!")) content.email = check_email(to_save["email"]) - # Query User name, if not existing, change + # Query username, if not existing, change content.name = check_username(to_save["name"]) if to_save.get("kindle_mail"): content.kindle_mail = valid_email(to_save["kindle_mail"]) @@ -1956,7 +1958,7 @@ def _handle_edit_user(to_save, content, languages, translations, kobo_support): try: if to_save.get("email", content.email) != content.email: content.email = check_email(to_save["email"]) - # Query User name, if not existing, change + # Query username, if not existing, change if to_save.get("name", content.name) != content.name: if to_save.get("name") == "Guest": raise Exception(_("Guest Name can't be changed")) diff --git a/cps/babel.py b/cps/babel.py index f5ecaf5a..4da808bc 100644 --- a/cps/babel.py +++ b/cps/babel.py @@ -32,8 +32,10 @@ def get_locale(): def get_user_locale_language(user_language): return Locale.parse(user_language).get_language_name(get_locale()) + def get_available_locale(): return [Locale('en')] + babel.list_translations() + def get_available_translations(): return set(str(item) for item in get_available_locale()) diff --git a/cps/cache_buster.py b/cps/cache_buster.py index ba19afd6..0a036b63 100644 --- a/cps/cache_buster.py +++ b/cps/cache_buster.py @@ -49,7 +49,7 @@ def init_cache_busting(app): rooted_filename = os.path.join(dirpath, filename) try: with open(rooted_filename, 'rb') as f: - file_hash = hashlib.md5(f.read()).hexdigest()[:7] # nosec + file_hash = hashlib.md5(f.read()).hexdigest()[:7] # nosec # save version to tables file_path = rooted_filename.replace(static_folder, "") file_path = file_path.replace("\\", "/") # Convert Windows path to web path @@ -59,11 +59,11 @@ def init_cache_busting(app): log.debug('Finished computing cache-busting values') - def bust_filename(filename): - return hash_table.get(filename, "") + def bust_filename(file_name): + return hash_table.get(file_name, "") - def unbust_filename(filename): - return filename.split("?", 1)[0] + def unbust_filename(file_name): + return file_name.split("?", 1)[0] @app.url_defaults # pylint: disable=unused-variable @@ -76,11 +76,11 @@ def init_cache_busting(app): if file_hash: values["q"] = file_hash - def debusting_static_view(filename): + def debusting_static_view(file_name): """ Serve a request for a static file having a busted name. """ - return original_static_view(filename=unbust_filename(filename)) + return original_static_view(filename=unbust_filename(file_name)) # Replace the default static file view with our debusting view. original_static_view = app.view_functions["static"] diff --git a/cps/cli.py b/cps/cli.py index cf4f36fb..5896c7fe 100644 --- a/cps/cli.py +++ b/cps/cli.py @@ -26,26 +26,28 @@ from .constants import STABLE_VERSION as _STABLE_VERSION from .constants import NIGHTLY_VERSION as _NIGHTLY_VERSION from .constants import DEFAULT_SETTINGS_FILE, DEFAULT_GDRIVE_FILE + def version_info(): if _NIGHTLY_VERSION[1].startswith('$Format'): return "Calibre-Web version: %s - unkown git-clone" % _STABLE_VERSION['version'] return "Calibre-Web version: %s -%s" % (_STABLE_VERSION['version'], _NIGHTLY_VERSION[1]) + class CliParameter(object): def init(self): self.arg_parser() def arg_parser(self): - parser = argparse.ArgumentParser(description='Calibre Web is a web app' - ' providing a interface for browsing, reading and downloading eBooks\n', + parser = argparse.ArgumentParser(description='Calibre Web is a web app providing ' + 'a interface for browsing, reading and downloading eBooks\n', prog='cps.py') parser.add_argument('-p', metavar='path', help='path and name to settings db, e.g. /opt/cw.db') parser.add_argument('-g', metavar='path', help='path and name to gdrive db, e.g. /opt/gd.db') - parser.add_argument('-c', metavar='path', - help='path and name to SSL certfile, e.g. /opt/test.cert, works only in combination with keyfile') - parser.add_argument('-k', metavar='path', - help='path and name to SSL keyfile, e.g. /opt/test.key, works only in combination with certfile') + parser.add_argument('-c', metavar='path', help='path and name to SSL certfile, e.g. /opt/test.cert, ' + 'works only in combination with keyfile') + parser.add_argument('-k', metavar='path', help='path and name to SSL keyfile, e.g. /opt/test.key, ' + 'works only in combination with certfile') parser.add_argument('-v', '--version', action='version', help='Shows version number and exits Calibre-Web', version=version_info()) parser.add_argument('-i', metavar='ip-address', help='Server IP-Address to listen') @@ -67,7 +69,6 @@ class CliParameter(object): if os.path.isdir(self.gd_path): self.gd_path = os.path.join(self.gd_path, DEFAULT_GDRIVE_FILE) - # handle and check parameter for ssl encryption self.certfilepath = None self.keyfilepath = None @@ -96,7 +97,7 @@ class CliParameter(object): self.keyfilepath = "" # dry run updater - self.dry_run =args.d or None + self.dry_run = args.d or None # enable reconnect endpoint for docker database reconnect self.reconnect_enable = args.r or os.environ.get("CALIBRE_RECONNECT", None) # load covers from localhost @@ -112,7 +113,7 @@ class CliParameter(object): else: socket.inet_pton(socket.AF_INET, self.ip_address) else: - # on windows python < 3.4, inet_pton is not available + # on Windows python < 3.4, inet_pton is not available # inet_atom only handles IPv4 addresses socket.inet_aton(self.ip_address) except socket.error as err: diff --git a/cps/config_sql.py b/cps/config_sql.py index 405a92ec..bba3d650 100644 --- a/cps/config_sql.py +++ b/cps/config_sql.py @@ -35,6 +35,7 @@ from . import constants, logger log = logger.create() _Base = declarative_base() + class _Flask_Settings(_Base): __tablename__ = 'flask_settings' @@ -67,7 +68,7 @@ class _Settings(_Base): config_external_port = Column(Integer, default=constants.DEFAULT_PORT) config_certfile = Column(String) config_keyfile = Column(String) - config_trustedhosts = Column(String,default='') + config_trustedhosts = Column(String, default='') config_calibre_web_title = Column(String, default=u'Calibre-Web') config_books_per_page = Column(Integer, default=60) config_random_books = Column(Integer, default=4) @@ -123,7 +124,7 @@ class _Settings(_Base): config_ldap_key_path = Column(String, default="") config_ldap_dn = Column(String, default='dc=example,dc=org') config_ldap_user_object = Column(String, default='uid=%s') - config_ldap_member_user_object = Column(String, default='') # + config_ldap_member_user_object = Column(String, default='') config_ldap_openldap = Column(Boolean, default=True) config_ldap_group_object_filter = Column(String, default='(&(objectclass=posixGroup)(cn=%s))') config_ldap_group_members_field = Column(String, default='memberUid') @@ -171,7 +172,6 @@ class _ConfigSQL(object): self.config_converterpath = autodetect_calibre_binary() if self.config_kepubifypath == None: # pylint: disable=access-member-before-definition - change = True self.config_kepubifypath = autodetect_kepubify_binary() @@ -257,14 +257,14 @@ class _ConfigSQL(object): return logger.get_level_name(self.config_log_level) def get_mail_settings(self): - return {k:v for k, v in self.__dict__.items() if k.startswith('mail_')} + return {k: v for k, v in self.__dict__.items() if k.startswith('mail_')} def get_mail_server_configured(self): return bool((self.mail_server != constants.DEFAULT_MAIL_SERVER and self.mail_server_type == 0) or (self.mail_gmail_token != {} and self.mail_server_type == 1)) def get_scheduled_task_settings(self): - return {k:v for k, v in self.__dict__.items() if k.startswith('schedule_')} + return {k: v for k, v in self.__dict__.items() if k.startswith('schedule_')} def set_from_dictionary(self, dictionary, field, convertor=None, default=None, encode=None): """Possibly updates a field of this object. @@ -301,7 +301,7 @@ class _ConfigSQL(object): return storage def load(self): - '''Load all configuration values from the underlying storage.''' + """Load all configuration values from the underlying storage.""" s = self._read_from_storage() # type: _Settings for k, v in s.__dict__.items(): if k[0] != '_': @@ -334,7 +334,7 @@ class _ConfigSQL(object): self._session.rollback() def save(self): - '''Apply all configuration values to the underlying storage.''' + """Apply all configuration values to the underlying storage.""" s = self._read_from_storage() # type: _Settings for k, v in self.__dict__.items(): @@ -369,6 +369,7 @@ class _ConfigSQL(object): except AttributeError: pass + def _migrate_table(session, orm_class): changed = False @@ -390,9 +391,9 @@ def _migrate_table(session, orm_class): else: column_type = column.type alter_table = text("ALTER TABLE %s ADD COLUMN `%s` %s %s" % (orm_class.__tablename__, - column_name, - column_type, - column_default)) + column_name, + column_type, + column_default)) log.debug(alter_table) session.execute(alter_table) changed = True @@ -462,6 +463,7 @@ def load_configuration(conf, session, cli): conf.init_config(session, cli) # return conf + def get_flask_session_key(_session): flask_settings = _session.query(_Flask_Settings).one_or_none() if flask_settings == None: diff --git a/cps/converter.py b/cps/converter.py index af2a6c09..981b3909 100644 --- a/cps/converter.py +++ b/cps/converter.py @@ -54,10 +54,9 @@ def get_calibre_version(): def get_unrar_version(): unrar_version = _get_command_version(config.config_rarfile_location, r'UNRAR.*\d') if unrar_version == "not installed": - unrar_version = _get_command_version(config.config_rarfile_location, r'unrar.*\d','-V') + unrar_version = _get_command_version(config.config_rarfile_location, r'unrar.*\d', '-V') return unrar_version + def get_kepubify_version(): - return _get_command_version(config.config_kepubifypath, r'kepubify\s','--version') - - + return _get_command_version(config.config_kepubifypath, r'kepubify\s', '--version') diff --git a/cps/debug_info.py b/cps/debug_info.py index dd5e858e..64fda557 100644 --- a/cps/debug_info.py +++ b/cps/debug_info.py @@ -32,6 +32,7 @@ from .about import collect_stats log = logger.create() + def assemble_logfiles(file_name): log_list = sorted(glob.glob(file_name + '*'), reverse=True) wfd = BytesIO() diff --git a/cps/dep_check.py b/cps/dep_check.py index 44f3961a..bc015756 100644 --- a/cps/dep_check.py +++ b/cps/dep_check.py @@ -42,7 +42,7 @@ def load_dependencies(optional=False): res = re.match(r'(.*?)([<=>\s]+)([\d\.]+),?\s?([<=>\s]+)?([\d\.]+)?', line.strip()) try: if getattr(sys, 'frozen', False): - dep_version = exe_deps[res.group(1).lower().replace('_','-')] + dep_version = exe_deps[res.group(1).lower().replace('_', '-')] else: if importlib: dep_version = version(res.group(1)) diff --git a/cps/logger.py b/cps/logger.py index 82853bba..13535efb 100644 --- a/cps/logger.py +++ b/cps/logger.py @@ -54,7 +54,6 @@ class _Logger(logging.Logger): else: self.error(message, *args, **kwargs) - def debug_no_auth(self, message, *args, **kwargs): message = message.strip("\r\n") if message.startswith("send: AUTH"): @@ -66,6 +65,7 @@ class _Logger(logging.Logger): def get(name=None): return logging.getLogger(name) + def create(): parent_frame = inspect.stack(0)[1] if hasattr(parent_frame, 'frame'): @@ -75,9 +75,11 @@ def create(): parent_module = inspect.getmodule(parent_frame) return get(parent_module.__name__) + def is_debug_enabled(): return logging.root.level <= logging.DEBUG + def is_info_enabled(logger): return logging.getLogger(logger).level <= logging.INFO @@ -114,10 +116,10 @@ def get_accesslogfile(log_file): def setup(log_file, log_level=None): - ''' + """ Configure the logging output. May be called multiple times. - ''' + """ log_level = log_level or DEFAULT_LOG_LEVEL logging.setLoggerClass(_Logger) logging.getLogger(__package__).setLevel(log_level) @@ -127,7 +129,7 @@ def setup(log_file, log_level=None): # avoid spamming the log with debug messages from libraries r.setLevel(log_level) - # Otherwise name get's destroyed on windows + # Otherwise, name gets destroyed on Windows if log_file != LOG_TO_STDERR and log_file != LOG_TO_STDOUT: log_file = _absolute_log_file(log_file, DEFAULT_LOG_FILE) @@ -164,9 +166,9 @@ def setup(log_file, log_level=None): def create_access_log(log_file, log_name, formatter): - ''' + """ One-time configuration for the web server's access log. - ''' + """ log_file = _absolute_log_file(log_file, DEFAULT_ACCESS_LOG) logging.debug("access log: %s", log_file) @@ -183,8 +185,7 @@ def create_access_log(log_file, log_name, formatter): file_handler.setFormatter(formatter) access_log.addHandler(file_handler) - return access_log, \ - "" if _absolute_log_file(log_file, DEFAULT_ACCESS_LOG) == DEFAULT_ACCESS_LOG else log_file + return access_log, "" if _absolute_log_file(log_file, DEFAULT_ACCESS_LOG) == DEFAULT_ACCESS_LOG else log_file # Enable logging of smtp lib debug output