From cb82b1f3c7f445c47186910dcf6083f034866414 Mon Sep 17 00:00:00 2001 From: Alex Laird Date: Sun, 11 Feb 2024 14:25:21 -0600 Subject: [PATCH] Migrate to f-strings where convenient. --- hookee/cli.py | 24 +++++++++++----------- hookee/conf.py | 2 +- hookee/hookeemanager.py | 10 ++++----- hookee/pluginmanager.py | 22 ++++++++------------ hookee/plugins/request_body.py | 2 +- hookee/plugins/request_headers.py | 2 +- hookee/plugins/request_url_info.py | 9 +++++--- hookee/plugins/response_info.py | 4 ++-- hookee/server.py | 6 +++--- hookee/tunnel.py | 2 +- hookee/util.py | 8 ++++---- tests/managedtestcase.py | 2 +- tests/plugins_dir/custom_plugin.py | 7 +++++-- tests/plugins_dir/custom_request_plugin.py | 2 +- tests/test_hookee_manager_edges.py | 2 +- 15 files changed, 53 insertions(+), 51 deletions(-) diff --git a/hookee/cli.py b/hookee/cli.py index 403b143..9e55d84 100644 --- a/hookee/cli.py +++ b/hookee/cli.py @@ -48,7 +48,7 @@ def hookee(ctx, **kwargs): hookee documentation can be found at https://hookee.readthedocs.io. """ if kwargs["version"]: - ctx.exit("hookee/{} Python/{}".format(VERSION, platform.python_version())) + ctx.exit(f"hookee/{VERSION} Python/{platform.python_version()}") ctx.ensure_object(dict) for key, value in kwargs.items(): @@ -105,9 +105,9 @@ def update_config(ctx, key, value): hookee_manager.config.set(key, value) hookee_manager.print_util.print_config_update( - "The default value for \"{}\" has been updated in the config.".format(key)) + f"The default value for \"{key}\" has been updated in the config.") except KeyError: - ctx.fail("No such key exists in the config: {}".format(key)) + ctx.fail(f"No such key exists in the config: {key}") @hookee.command() @@ -123,7 +123,7 @@ def enable_plugin(ctx, plugin): hookee_manager.config.append("plugins", plugin) - hookee_manager.print_util.print_config_update("Plugin \"{}\" has been enabled.".format(plugin)) + hookee_manager.print_util.print_config_update(f"Plugin \"{plugin}\" has been enabled.") @hookee.command() @@ -136,11 +136,11 @@ def disable_plugin(ctx, plugin): hookee_manager = ctx.obj["hookee_manager"] if plugin in pluginmanager.REQUIRED_PLUGINS: - ctx.fail("Can't disable the plugin \"{}\".".format(plugin)) + ctx.fail(f"Can't disable the plugin \"{plugin}\".") hookee_manager.config.remove("plugins", plugin) - hookee_manager.print_util.print_config_update("Plugin \"{}\" is disabled.".format(plugin)) + hookee_manager.print_util.print_config_update(f"Plugin \"{plugin}\" is disabled.") @hookee.command() @@ -156,14 +156,14 @@ def available_plugins(ctx): hookee_manager.print_util.print_open_header("Available Plugins") for plugin_name in plugins: - hookee_manager.print_util.print_basic(" * {}".format(plugin_name)) + hookee_manager.print_util.print_basic(f" * {plugin_name}") try: plugin = hookee_manager.plugin_manager.get_plugin(plugin_name) if plugin.description: - hookee_manager.print_util.print_basic(" Description: {}".format(plugin.description)) + hookee_manager.print_util.print_basic(f" Description: {plugin.description}") except Exception as e: - hookee_manager.print_util.print_basic(" Error: {}".format(e)) + hookee_manager.print_util.print_basic(f" Error: {e}") hookee_manager.print_util.print_close_header() hookee_manager.print_util.print_basic() @@ -182,14 +182,14 @@ def enabled_plugins(ctx): hookee_manager.print_util.print_open_header("Enabled Plugins (Order of Execution)") for plugin_name in plugins: - hookee_manager.print_util.print_basic(" * {}".format(plugin_name)) + hookee_manager.print_util.print_basic(f" * {plugin_name}") try: plugin = hookee_manager.plugin_manager.get_plugin(plugin_name) if plugin.description: - hookee_manager.print_util.print_basic(" Description: {}".format(plugin.description)) + hookee_manager.print_util.print_basic(f" Description: {plugin.description}") except Exception as e: - hookee_manager.print_util.print_basic(" Error: {}".format(e)) + hookee_manager.print_util.print_basic(f" Error: {e}") hookee_manager.print_util.print_close_header() hookee_manager.print_util.print_basic() diff --git a/hookee/conf.py b/hookee/conf.py index fdd6bbd..20e8b3c 100644 --- a/hookee/conf.py +++ b/hookee/conf.py @@ -108,7 +108,7 @@ def __init__(self, click_logging=None, **kwargs): if not os.path.exists(plugins_dir): os.makedirs(plugins_dir) except confuse.NotFoundError as e: - raise HookeeConfigError("The config file is invalid: {}.".format(str(e))) + raise HookeeConfigError(f"The config file is invalid: {str(e)}.") except (confuse.ConfigReadError, ValueError): raise HookeeConfigError("The config file is not valid YAML.") diff --git a/hookee/hookeemanager.py b/hookee/hookeemanager.py index ece2ae3..73134d8 100644 --- a/hookee/hookeemanager.py +++ b/hookee/hookeemanager.py @@ -120,13 +120,13 @@ def stop(self): def print_hookee_banner(self): self.print_util.print_open_header("", "=") - self.print_util.print_basic(""" .__ __ + self.print_util.print_basic(f""" .__ __ | |__ ____ ____ | | __ ____ ____ | | \ / _ \ / _ \| |/ // __ \_/ __ \ | Y ( <_> | <_> ) <\ ___/\ ___/ |___| /\____/ \____/|__|_ \\___ >\___ > \/ \/ \/ \/ - v{}""".format(VERSION), color="green", bold=True) + v{VERSION}""", color="green", bold=True) self.print_util.print_basic() self.print_util.print_close_header("=", blank_line=False) @@ -134,7 +134,7 @@ def print_ready(self): self.print_util.print_open_header("Registered Plugins") plugins = self.plugin_manager.enabled_plugins() - self.print_util.print_basic(" * Enabled Plugins: {}".format(plugins)) + self.print_util.print_basic(f" * Enabled Plugins: {plugins}") if self.plugin_manager.response_callback: self.print_util.print_basic(" Response callback: enabled") @@ -145,8 +145,8 @@ def print_ready(self): rules = list(filter(lambda r: r.rule not in ["/shutdown", "/static/", "/status"], self.server.app.url_map.iter_rules())) for rule in rules: - self.print_util.print_basic(" * {}{}".format(self.tunnel.public_url, rule.rule), print_when_logging=True) - self.print_util.print_basic(" Methods: {}".format(sorted(list(rule.methods))), print_when_logging=True) + self.print_util.print_basic(f" * {self.tunnel.public_url}{rule.rule}", print_when_logging=True) + self.print_util.print_basic(f" Methods: {sorted(list(rule.methods))}", print_when_logging=True) self.print_util.print_close_header() diff --git a/hookee/pluginmanager.py b/hookee/pluginmanager.py index 231c606..89902c5 100644 --- a/hookee/pluginmanager.py +++ b/hookee/pluginmanager.py @@ -87,30 +87,27 @@ def build_from_module(module): if "plugin_type" not in attributes: raise HookeePluginValidationError( - "Plugin \"{}\" does not conform to the plugin spec.".format(name)) + f"Plugin \"{name}\" does not conform to the plugin spec.") elif module.plugin_type not in VALID_PLUGIN_TYPES: raise HookeePluginValidationError( - "Plugin \"{}\" must specify a valid `plugin_type`.".format(name)) + f"Plugin \"{name}\" must specify a valid `plugin_type`.") elif module.plugin_type == REQUEST_PLUGIN: if "run" not in functions_list: raise HookeePluginValidationError( - "Plugin \"{}\" must implement `run(request)`.".format(name)) + f"Plugin \"{name}\" must implement `run(request)`.") elif len(util.get_args(module.run)) < 1: raise HookeePluginValidationError( - "Plugin \"{}\" does not conform to the plugin spec, `run(request)` must be defined.".format( - name)) + f"Plugin \"{name}\" does not conform to the plugin spec, `run(request)` must be defined.") elif module.plugin_type == RESPONSE_PLUGIN: if "run" not in functions_list: raise HookeePluginValidationError( - "Plugin \"{}\" must implement `run(request, response)`.".format(name)) + f"Plugin \"{name}\" must implement `run(request, response)`.") elif len(util.get_args(module.run)) < 2: raise HookeePluginValidationError( - "Plugin \"{}\" does not conform to the plugin spec, `run(request, response)` must be defined.".format( - name)) + f"Plugin \"{name}\" does not conform to the plugin spec, `run(request, response)` must be defined.") elif module.plugin_type == BLUEPRINT_PLUGIN and "blueprint" not in attributes: raise HookeePluginValidationError( - "Plugin \"{}\" must define `blueprint = Blueprint(\"plugin_name\", __name__)`.".format( - name)) + "Plugin \"{name}\" must define `blueprint = Blueprint(\"plugin_name\", __name__)`.") has_setup = "setup" in functions_list and len(util.get_args(module.setup)) == 1 @@ -190,8 +187,7 @@ def load_plugins(self): for plugin_name in REQUIRED_PLUGINS: if plugin_name not in enabled_plugins: self.hookee_manager.fail( - "Sorry, the plugin {} is required. Run `hookee enable-plugin {}` before continuing.".format( - plugin_name, plugin_name)) + f"Sorry, the plugin {plugin_name} is required. Run `hookee enable-plugin {plugin_name}` before continuing.") self.source_plugins() @@ -307,7 +303,7 @@ def get_plugin(self, plugin_name, throw_error=False): if throw_error: raise e - self.hookee_manager.fail("Plugin \"{}\" could not be found.".format(plugin_name)) + self.hookee_manager.fail(f"Plugin \"{plugin_name}\" could not be found.") except HookeePluginValidationError as e: if throw_error: raise e diff --git a/hookee/plugins/request_body.py b/hookee/plugins/request_body.py index 3826e1c..c607c1f 100644 --- a/hookee/plugins/request_body.py +++ b/hookee/plugins/request_body.py @@ -25,6 +25,6 @@ def run(request): print_util.print_basic("Body Type: FORM") print_util.print_dict("Body", dict(request.form), color=print_util.request_color) elif request.data: - print_util.print_basic("Body: {}".format(request.data.decode("utf-8")), color=print_util.request_color) + print_util.print_basic(f"Body: {request.data.decode('utf-8')}", color=print_util.request_color) return request diff --git a/hookee/plugins/request_headers.py b/hookee/plugins/request_headers.py index e0450be..74a4404 100644 --- a/hookee/plugins/request_headers.py +++ b/hookee/plugins/request_headers.py @@ -19,7 +19,7 @@ def setup(hookee_manager): def run(request): if request.headers and "X-Forwarded-For" in request.headers: - print_util.print_basic("Client IP: {}".format(request.headers.get("X-Forwarded-For")), + print_util.print_basic(f"Client IP: {request.headers.get('X-Forwarded-For')}", color=print_util.request_color) if request.headers: print_util.print_dict("Headers", dict(request.headers), color=print_util.request_color) diff --git a/hookee/plugins/request_url_info.py b/hookee/plugins/request_url_info.py index ce14f0e..60dd02f 100644 --- a/hookee/plugins/request_url_info.py +++ b/hookee/plugins/request_url_info.py @@ -24,9 +24,12 @@ def run(request): timestamp = now.strftime("%m-%d-%Y %I:%M:%S %p") - print_util.print_basic("[{}] \"{} {} {}\"".format(timestamp, request.method, request.base_url, - request.environ["SERVER_PROTOCOL"]), - color=print_util.request_color, bold=True) + print_util.print_basic( + "[{timestamp}] \"{method} {url} {protocol}\"".format(timestamp=timestamp, + method=request.method, + url=request.base_url, + protocol=request.environ["SERVER_PROTOCOL"]), + color=print_util.request_color, bold=True) print_util.print_basic() return request diff --git a/hookee/plugins/response_info.py b/hookee/plugins/response_info.py index 4e5ddf0..101d292 100644 --- a/hookee/plugins/response_info.py +++ b/hookee/plugins/response_info.py @@ -18,13 +18,13 @@ def setup(hookee_manager): def run(request, response): - print_util.print_basic("Status Code: {}".format(response.status_code), color=print_util.request_color) + print_util.print_basic(f"Status Code: {response.status_code}", color=print_util.request_color) if response.headers: print_util.print_dict("Headers", dict(response.headers), color=print_util.request_color) if response.data: if response.is_json: print_util.print_dict("Body", response.get_json(), color=print_util.request_color) else: - print_util.print_basic("Body: {}".format(response.data.decode("utf-8")), color=print_util.request_color) + print_util.print_basic(f"Body: {response.data.decode('utf-8')}", color=print_util.request_color) return response diff --git a/hookee/server.py b/hookee/server.py index 3c8656c..a39bbdd 100644 --- a/hookee/server.py +++ b/hookee/server.py @@ -98,7 +98,7 @@ def stop(self): If running, kill the server and cleanup its thread. """ if self._thread: - req = Request("http://127.0.0.1:{}/shutdown".format(self.port), method="POST") + req = Request(f"http://127.0.0.1:{self.port}/shutdown", method="POST") urlopen(req) self._thread = None @@ -111,11 +111,11 @@ def _server_status(self): :rtype: http.HTTPStatus """ try: - return urlopen("http://127.0.0.1:{}/status".format(self.port)).getcode() + return urlopen(f"http://127.0.0.1:{self.port}/status").getcode() except URLError: return HTTPStatus.INTERNAL_SERVER_ERROR def print_close_header(self): - self.print_util.print_basic(" * Port: {}".format(self.port)) + self.print_util.print_basic(f" * Port: {self.port}") self.print_util.print_basic(" * Blueprints: registered") self.print_util.print_close_header() diff --git a/hookee/tunnel.py b/hookee/tunnel.py index 37c4e85..97ce1ed 100644 --- a/hookee/tunnel.py +++ b/hookee/tunnel.py @@ -111,6 +111,6 @@ def stop(self): def print_close_header(self): self.print_util.print_basic( - " * Tunnel: {} -> http://127.0.0.1:{}".format(self.public_url, self.port), + f" * Tunnel: {self.public_url} -> http://127.0.0.1:{self.port}", print_when_logging=True) self.print_util.print_close_header() diff --git a/hookee/util.py b/hookee/util.py index dee21bb..17e557f 100644 --- a/hookee/util.py +++ b/hookee/util.py @@ -55,7 +55,7 @@ def request_color(self): return self.config.get("request_color") def print_config_update(self, msg): - self.print_basic("\n--> {}\n".format(msg), color=self.header_color) + self.print_basic(f"\n--> {msg}\n", color=self.header_color) def print_open_header(self, title, delimiter="-", color=None): """ @@ -74,7 +74,7 @@ def print_open_header(self, title, delimiter="-", color=None): width = int((self.console_width - len(title)) / 2) self.print_basic() - self.print_basic("{}{}{}".format(delimiter * width, title, delimiter * width), color=color, bold=True) + self.print_basic(f"{delimiter * width}{title}{delimiter * width}", color=color, bold=True) self.print_basic() def print_close_header(self, delimiter="-", color=None, blank_line=True): @@ -109,7 +109,7 @@ def print_dict(self, title, data, color=None): if color is None: color = self.default_color - self.print_basic("{}: {}".format(title, json.dumps(data, indent=4)), color=color) + self.print_basic(f"{title}: {json.dumps(data, indent=4)}", color=color) def print_xml(self, title, data, color=None): """ @@ -125,7 +125,7 @@ def print_xml(self, title, data, color=None): if color is None: color = self.default_color - self.print_basic("{}: {}".format(title, parseString(data).toprettyxml()), color=color) + self.print_basic(f"{title}: {parseString(data).toprettyxml()}", color=color) def print_basic(self, msg="", color=None, bold=False, print_when_logging=False): """ diff --git a/tests/managedtestcase.py b/tests/managedtestcase.py index 73e6840..4d0ac18 100644 --- a/tests/managedtestcase.py +++ b/tests/managedtestcase.py @@ -18,7 +18,7 @@ class ManagedTestCase(HookeeTestCase): def setUp(self): super(ManagedTestCase, self).setUp() - self.webhook_url = "{}/webhook".format(self.hookee_manager.tunnel.public_url) + self.webhook_url = f"{self.hookee_manager.tunnel.public_url}/webhook" @classmethod def setUpClass(cls): diff --git a/tests/plugins_dir/custom_plugin.py b/tests/plugins_dir/custom_plugin.py index 2ed545d..adee622 100644 --- a/tests/plugins_dir/custom_plugin.py +++ b/tests/plugins_dir/custom_plugin.py @@ -24,8 +24,11 @@ def run(request): timestamp = now.strftime("%m-%d-%Y %I:%M:%S %p") - print_util.print_basic("[{}] \"{} {} {}\"".format(timestamp, request.method, request.base_url, - request.environ["SERVER_PROTOCOL"]), + print_util.print_basic("[{timestamp}] \"{method} {url} {protocol}\"".format(timestamp=timestamp, + method=request.method, + url=request.base_url, + protocol=request.environ[ + "SERVER_PROTOCOL"]), color=print_util.request_color, bold=True) print_util.print_basic() diff --git a/tests/plugins_dir/custom_request_plugin.py b/tests/plugins_dir/custom_request_plugin.py index a076edd..93092f0 100644 --- a/tests/plugins_dir/custom_request_plugin.py +++ b/tests/plugins_dir/custom_request_plugin.py @@ -25,6 +25,6 @@ def run(request): print_util.print_basic("Body Type: FORM") print_util.print_dict("Body", dict(request.form), color=print_util.request_color) elif request.data: - print_util.print_basic("Body: {}".format(request.data.decode("utf-8")), color=print_util.request_color) + print_util.print_basic(f"Body: {request.data.decode('utf-8')}", color=print_util.request_color) return request diff --git a/tests/test_hookee_manager_edges.py b/tests/test_hookee_manager_edges.py index 118b8b3..3ee344c 100644 --- a/tests/test_hookee_manager_edges.py +++ b/tests/test_hookee_manager_edges.py @@ -41,7 +41,7 @@ def test_custom_response(self): hookee_manager = HookeeManager(config=config) hookee_manager._init_server_and_tunnel() - webhook_url = "{}/webhook".format(hookee_manager.tunnel.public_url) + webhook_url = f"{hookee_manager.tunnel.public_url}/webhook" # WHEN response = requests.get(webhook_url)