Skip to content

Commit

Permalink
Upgrade the Python syntax
Browse files Browse the repository at this point in the history
This second round is the result of the following commands:
`ruff check --fix --unsafe-fixes`
`ruff format`
  • Loading branch information
pgiraud committed Nov 13, 2024
1 parent 733afae commit 89a89d9
Show file tree
Hide file tree
Showing 16 changed files with 74 additions and 90 deletions.
23 changes: 11 additions & 12 deletions powa/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

"""
Powa main application.
"""
Expand Down Expand Up @@ -62,36 +61,36 @@ def make_app(**kwargs):
parse_options()

URLS = [
U(r"%slogin/" % options.url_prefix, LoginHandler, name="login"),
U(r"%slogout/" % options.url_prefix, LogoutHandler, name="logout"),
U(rf"{options.url_prefix}login/", LoginHandler, name="login"),
U(rf"{options.url_prefix}logout/", LogoutHandler, name="logout"),
U(
r"%sreload_collector/" % options.url_prefix,
rf"{options.url_prefix}reload_collector/",
CollectorReloadHandler,
name="reload_collector",
),
U(
r"%sforce_snapshot/(\d+)" % options.url_prefix,
rf"{options.url_prefix}force_snapshot/(\d+)",
CollectorForceSnapshotHandler,
name="force_snapshot",
),
U(
r"%srefresh_db_cat/" % options.url_prefix,
rf"{options.url_prefix}refresh_db_cat/",
CollectorDbCatRefreshHandler,
name="refresh_db_cat",
),
U(
r"%sserver/select" % options.url_prefix,
rf"{options.url_prefix}server/select",
ServerSelector,
name="server_selector",
),
U(
r"%sdatabase/select" % options.url_prefix,
rf"{options.url_prefix}database/select",
DatabaseSelector,
name="database_selector",
),
U(r"%s" % options.url_prefix, IndexHandler, name="index"),
U(rf"{options.url_prefix}", IndexHandler, name="index"),
U(
r"%sserver/(\d+)/database/([^\/]+)/suggest/" % options.url_prefix,
rf"{options.url_prefix}server/(\d+)/database/([^\/]+)/suggest/",
IndexSuggestionHandler,
name="index_suggestion",
),
Expand Down Expand Up @@ -123,9 +122,9 @@ def make_app(**kwargs):
URLS,
ui_modules=ui_modules,
ui_methods=ui_methods,
login_url=("%slogin/" % options.url_prefix),
login_url=(f"{options.url_prefix}login/"),
static_path=os.path.join(POWA_ROOT, "static"),
static_url_prefix=("%sstatic/" % options.url_prefix),
static_url_prefix=(f"{options.url_prefix}static/"),
cookie_secret=options.cookie_secret,
template_path=os.path.join(POWA_ROOT, "templates"),
**kwargs,
Expand Down
1 change: 0 additions & 1 deletion powa/collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
collector handling.
"""


import json
from powa.dashboards import MetricGroupDef
from powa.framework import AuthHandler
Expand Down
1 change: 0 additions & 1 deletion powa/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
"""


import json
import psycopg2
from psycopg2 import extensions
Expand Down
5 changes: 2 additions & 3 deletions powa/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
Dashboard for the configuration summary page.
"""


import json
from powa.collector import CollectorServerDetail
from powa.dashboards import (
Expand Down Expand Up @@ -417,7 +416,7 @@ def post_process(self, data, server, **kwargs):
data["messages"] = {
"alert": [
"Could not retrieve extensions"
+ " on remote server: %s" % errmsg
+ f" on remote server: {errmsg}"
]
}
return data
Expand Down Expand Up @@ -527,7 +526,7 @@ def post_process(self, data, server, **kwargs):
data["messages"] = {
"alert": [
"Could not retrieve extensions"
+ " on remote server: %s" % errmsg
+ f" on remote server: {errmsg}"
]
}
return data
Expand Down
21 changes: 11 additions & 10 deletions powa/dashboards.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ def url_name(cls):
"""
Returns the default url_name for this data source.
"""
return "datasource_%s" % cls.__name__
return f"datasource_{cls.__name__}"

@classproperty
def parameterized_json(cls, handler, **parms):
Expand Down Expand Up @@ -310,14 +310,14 @@ def bind(self, group):
"""

if self._group is not None:
raise ValueError("Already bound to %s" % self._group)
raise ValueError(f"Already bound to {self._group}")
self._group = group

def _fqn(self):
"""
Return the fully qualified name of this metric.
"""
return "%s.%s" % (self._group.name, self.name)
return f"{self._group.name}.{self.name}"


class Dashboard(JSONizable):
Expand Down Expand Up @@ -502,7 +502,7 @@ def _validate(self):
if any(m._group != mg1 for m in self.metrics):
raise ValueError(
"A grid is not allowed to have metrics from different "
"groups. (title: %s)" % self.title
f"groups. (title: {self.title})"
)

def to_json(self):
Expand Down Expand Up @@ -606,12 +606,12 @@ def __new__(meta, name, bases, dct):
if isinstance(val, Metric):
dct.pop(key)
dct["metrics"][key] = val
return super(MetaMetricGroup, meta).__new__(meta, name, bases, dct)
return super().__new__(meta, name, bases, dct)

def __init__(cls, name, bases, dct):
for metric in dct.get("metrics").values():
metric.bind(cls)
super(MetaMetricGroup, cls).__init__(name, bases, dct)
super().__init__(name, bases, dct)

def __getattr__(cls, key):
if key not in cls.metrics:
Expand Down Expand Up @@ -745,7 +745,7 @@ def url_specs(cls, url_prefix):
url_specs = []
url_specs.append(
URLSpec(
r"%s%s/" % (url_prefix, cls.base_url.strip("/")),
r"{}{}/".format(url_prefix, cls.base_url.strip("/")),
type(cls.__name__, (cls.dashboard_handler_cls, cls), {}),
{"template": cls.template, "params": cls.params},
name=cls.__name__,
Expand All @@ -754,12 +754,13 @@ def url_specs(cls, url_prefix):
for datasource in cls.datasources:
if datasource.data_url is None:
raise KeyError(
"A Datasource must have a data_url: %s"
% datasource.__name__
f"A Datasource must have a data_url: {datasource.__name__}"
)
url_specs.append(
URLSpec(
r"%s%s/" % (url_prefix, datasource.data_url.strip("/")),
r"{}{}/".format(
url_prefix, datasource.data_url.strip("/")
),
type(
datasource.__name__,
(datasource, datasource.datasource_handler_cls),
Expand Down
38 changes: 17 additions & 21 deletions powa/framework.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def cursor(self, *args, **kwargs):
elif factory == RealDictCursor:
kwargs["cursor_factory"] = CustomDictCursor
else:
msg = "Unsupported cursor_factory: %s" % factory.__name__
msg = f"Unsupported cursor_factory: {factory.__name__}"
self._logger.error(msg)
raise Exception(msg)

Expand All @@ -65,7 +65,7 @@ def execute(self, query, params=None):

self.timestamp = time.time()
try:
return super(CustomDictCursor, self).execute(query, params)
return super().execute(query, params)
except Exception as e:
log_query(self, query, params, e)
raise e
Expand All @@ -79,7 +79,7 @@ def execute(self, query, params=None):

self.timestamp = time.time()
try:
return super(CustomCursor, self).execute(query, params)
return super().execute(query, params)
except Exception as e:
log_query(self, query, params, e)
finally:
Expand Down Expand Up @@ -122,7 +122,7 @@ class BaseHandler(RequestHandler, JSONizable):
"""

def __init__(self, *args, **kwargs):
super(BaseHandler, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.flashed_messages = {}
self._databases = None
self._servers = None
Expand All @@ -135,11 +135,7 @@ def __init__(self, *args, **kwargs):

def __get_url(self, **connoptions):
url = " ".join(
[
"%s=%s" % (k, v)
for (k, v) in connoptions.items()
if v is not None
]
[f"{k}={v}" for (k, v) in connoptions.items() if v is not None]
)

return url
Expand Down Expand Up @@ -195,7 +191,7 @@ def current_host(self):
host = "localhost"
if "host" in connoptions:
host = connoptions["host"]
return "%s" % (host)
return f"{host}"

@property
def current_port(self):
Expand All @@ -209,7 +205,7 @@ def current_port(self):
port = "5432"
if "port" in connoptions:
port = connoptions["port"]
return "%s" % (port)
return f"{port}"

@property
def current_connection(self):
Expand All @@ -226,7 +222,7 @@ def current_connection(self):
host = connoptions["host"]
if "port" in connoptions:
port = connoptions["port"]
return "%s:%s" % (host, port)
return f"{host}:{port}"

@property
def database(self):
Expand Down Expand Up @@ -368,7 +364,7 @@ def connect(
user = user or self.get_str_cookie("user")
password = password or self.get_str_cookie("password")
if server not in options.servers:
raise HTTPError(404, "Server %s not found." % server)
raise HTTPError(404, f"Server {server} not found.")

connoptions = options.servers[server].copy()

Expand All @@ -378,14 +374,14 @@ def connect(
if encoding_query is not None:
if not isinstance(encoding_query, dict):
raise Exception(
'Invalid "query" parameter: %r, ' % encoding_query
f'Invalid "query" parameter: {encoding_query!r}, '
)

for k in encoding_query:
if k != "client_encoding":
raise Exception(
'Invalid "query" parameter: %r", '
'unexpected key "%s"' % (encoding_query, k)
f'Invalid "query" parameter: {encoding_query!r}", '
f'unexpected key "{k}"'
)

if srvid is not None and srvid != "0":
Expand Down Expand Up @@ -609,7 +605,7 @@ def write_error(self, status_code, **kwargs):
self._status_code = status_code
self.render("xhr.html", content=kwargs["exc_info"][1].log_message)
return
super(BaseHandler, self).write_error(status_code, **kwargs)
super().write_error(status_code, **kwargs)

def execute(
self,
Expand Down Expand Up @@ -669,11 +665,11 @@ def notify_collector(self, command, args=[], timeout=3):

random.seed()
channel = "r%d" % random.randint(1, 99999)
cur.execute("LISTEN %s" % channel)
cur.execute(f"LISTEN {channel}")

# some commands will contain user-provided strings, so we need to
# properly escape the arguments.
payload = "%s %s %s" % (command, channel, " ".join(args))
payload = "{} {} {}".format(command, channel, " ".join(args))
cur.execute("NOTIFY powa_collector, %s", (payload,))

cur.close()
Expand Down Expand Up @@ -758,10 +754,10 @@ class AuthHandler(BaseHandler):

@authenticated
def prepare(self):
super(AuthHandler, self).prepare()
super().prepare()

def to_json(self):
return dict(
**super(AuthHandler, self).to_json(),
**super().to_json(),
**{"logoutUrl": self.reverse_url("logout")},
)
1 change: 0 additions & 1 deletion powa/json.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

from datetime import datetime
from decimal import Decimal
from json import JSONEncoder as BaseJSONEncoder
Expand Down
8 changes: 4 additions & 4 deletions powa/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ def parse_file(filepath):
except OSError:
pass
except Error as e:
print("Error parsing config file %s:" % filepath)
print("\t%s" % e)
print(f"Error parsing config file {filepath}:")
print(f"\t{e}")
sys.exit(-1)


Expand All @@ -75,7 +75,7 @@ def parse_options():
parse_file(options.config)
except Error as e:
print("Error parsing command line options:")
print("\t%s" % e)
print(f"\t{e}")
sys.exit(1)

for key in ("servers", "cookie_secret"):
Expand Down Expand Up @@ -105,7 +105,7 @@ def parse_options():
define(
"index_url",
type=str,
default="%sserver/" % getattr(options, "url_prefix", "/"),
default="{}server/".format(getattr(options, "url_prefix", "/")),
)

# we used to expect a field named "username", so accept "username" as an
Expand Down
2 changes: 1 addition & 1 deletion powa/qual.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def get(self, server, database, query, qual):
)
except Exception as e:
raise HTTPError(
501, "Could not connect to remote server: %s" % str(e)
501, f"Could not connect to remote server: {str(e)}"
)
stmt = qualstat_getstatdata(
extra_select=["queryid = %(query)s AS is_my_query"],
Expand Down
Loading

0 comments on commit 89a89d9

Please sign in to comment.