Skip to content

Commit

Permalink
Migrate to f-strings where convenient.
Browse files Browse the repository at this point in the history
  • Loading branch information
alexdlaird committed Feb 11, 2024
1 parent 6e56537 commit cb82b1f
Show file tree
Hide file tree
Showing 15 changed files with 53 additions and 51 deletions.
24 changes: 12 additions & 12 deletions hookee/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -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()
Expand All @@ -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()
Expand All @@ -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()
Expand All @@ -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()
Expand All @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion hookee/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")

Expand Down
10 changes: 5 additions & 5 deletions hookee/hookeemanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,21 +120,21 @@ 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)

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")

Expand All @@ -145,8 +145,8 @@ def print_ready(self):
rules = list(filter(lambda r: r.rule not in ["/shutdown", "/static/<path:filename>", "/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()

Expand Down
22 changes: 9 additions & 13 deletions hookee/pluginmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion hookee/plugins/request_body.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion hookee/plugins/request_headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 6 additions & 3 deletions hookee/plugins/request_url_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 2 additions & 2 deletions hookee/plugins/response_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 3 additions & 3 deletions hookee/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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()
2 changes: 1 addition & 1 deletion hookee/tunnel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
8 changes: 4 additions & 4 deletions hookee/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand All @@ -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):
Expand Down Expand Up @@ -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):
"""
Expand All @@ -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):
"""
Expand Down
2 changes: 1 addition & 1 deletion tests/managedtestcase.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
7 changes: 5 additions & 2 deletions tests/plugins_dir/custom_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
2 changes: 1 addition & 1 deletion tests/plugins_dir/custom_request_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion tests/test_hookee_manager_edges.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit cb82b1f

Please sign in to comment.