apply pyupgrade fixes via ruff

ruff check --fix --select UP
This commit is contained in:
Min RK
2024-01-23 15:23:18 +01:00
parent 5e166970fa
commit e15b7c2620
18 changed files with 50 additions and 106 deletions

View File

@@ -25,6 +25,4 @@ import os
pg_pass = os.getenv('POSTGRES_ENV_JPY_PSQL_PASSWORD')
pg_host = os.getenv('POSTGRES_PORT_5432_TCP_ADDR')
c.JupyterHub.db_url = 'postgresql://jupyterhub:{}@{}:5432/jupyterhub'.format(
pg_pass, pg_host
)
c.JupyterHub.db_url = f'postgresql://jupyterhub:{pg_pass}@{pg_host}:5432/jupyterhub'

View File

@@ -11,7 +11,7 @@ c = get_config() # noqa
class DemoFormSpawner(LocalProcessSpawner):
def _options_form_default(self):
default_env = "YOURNAME=%s\n" % self.user.name
return """
return f"""
<div class="form-group">
<label for="args">Extra notebook CLI arguments</label>
<input name="args" class="form-control"
@@ -19,11 +19,9 @@ class DemoFormSpawner(LocalProcessSpawner):
</div>
<div class="form-group">
<label for="env">Environment variables (one per line)</label>
<textarea class="form-control" name="env">{env}</textarea>
<textarea class="form-control" name="env">{default_env}</textarea>
</div>
""".format(
env=default_env
)
"""
def options_from_form(self, formdata):
options = {}

View File

@@ -29,11 +29,10 @@ def upgrade():
# fill created date with current time
now = utcnow()
c.execute(
"""
f"""
UPDATE users
SET created='%s'
SET created='{now}'
"""
% (now,)
)
tables = sa.inspect(c.engine).get_table_names()
@@ -42,12 +41,11 @@ def upgrade():
op.add_column('spawners', sa.Column('started', sa.DateTime, nullable=True))
# fill started value with now for running servers
c.execute(
"""
f"""
UPDATE spawners
SET started='%s'
SET started='{now}'
WHERE server_id IS NOT NULL
"""
% (now,)
)

View File

@@ -40,7 +40,7 @@ class APIHandler(BaseHandler):
return 'application/json'
@property
@lru_cache()
@lru_cache
def accepts_pagination(self):
"""Return whether the client accepts the pagination preview media type"""
accept_header = self.request.headers.get("Accept", "")
@@ -460,8 +460,7 @@ class APIHandler(BaseHandler):
if not isinstance(value, model_types[key]):
raise web.HTTPError(
400,
"%s.%s must be %s, not: %r"
% (name, key, model_types[key], type(value)),
f"{name}.{key} must be {model_types[key]}, not: {type(value)!r}",
)
def _check_user_model(self, model):

View File

@@ -782,7 +782,7 @@ class SpawnProgressAPIHandler(APIHandler):
'progress': 100,
'ready': True,
'message': f"Server ready at {url}",
'html_message': 'Server ready at <a href="{0}">{0}</a>'.format(url),
'html_message': f'Server ready at <a href="{url}">{url}</a>',
'url': url,
}
original_ready_event = ready_event.copy()
@@ -881,9 +881,7 @@ def _parse_timestamp(timestamp):
if (dt - now) > timedelta(minutes=59):
raise web.HTTPError(
400,
"Rejecting activity from more than an hour in the future: {}".format(
isoformat(dt)
),
f"Rejecting activity from more than an hour in the future: {isoformat(dt)}",
)
return dt

View File

@@ -24,8 +24,6 @@ from textwrap import dedent
from typing import Optional
from urllib.parse import unquote, urlparse, urlunparse
if sys.version_info[:2] < (3, 3):
raise ValueError("Python < 3.3 not supported: %s" % sys.version)
import tornado.httpserver
import tornado.options
@@ -385,9 +383,7 @@ class JupyterHub(Application):
def _validate_config_file(self, proposal):
if not self.generate_config and not os.path.isfile(proposal.value):
print(
"ERROR: Failed to find specified config file: {}".format(
proposal.value
),
f"ERROR: Failed to find specified config file: {proposal.value}",
file=sys.stderr,
)
sys.exit(1)
@@ -1581,7 +1577,7 @@ class JupyterHub(Application):
if change.new:
self.log.warning(
dedent(
"""
f"""
extra_log_file is DEPRECATED in jupyterhub-0.8.2.
extra_log_file only redirects logs of the Hub itself,
@@ -1591,10 +1587,8 @@ class JupyterHub(Application):
It is STRONGLY recommended that you redirect process
output instead, e.g.
jupyterhub &>> '{}'
""".format(
change.new
)
jupyterhub &>> '{change.new}'
"""
)
)
@@ -1962,9 +1956,7 @@ class JupyterHub(Application):
if urlinfo.password:
# avoid logging the database password
urlinfo = urlinfo._replace(
netloc='{}:[redacted]@{}:{}'.format(
urlinfo.username, urlinfo.hostname, urlinfo.port
)
netloc=f'{urlinfo.username}:[redacted]@{urlinfo.hostname}:{urlinfo.port}'
)
db_log_url = urlinfo.geturl()
else:
@@ -3496,9 +3488,7 @@ class JupyterHub(Application):
self.internal_ssl = True
self.init_internal_ssl()
self.log.info(
"Certificates written to directory `{}`".format(
self.internal_certs_location
)
f"Certificates written to directory `{self.internal_certs_location}`"
)
loop.stop()
return

View File

@@ -820,13 +820,8 @@ def _deprecated_method(old_name, new_name, version):
def deprecated(self, *args, **kwargs):
warnings.warn(
(
"{cls}.{old_name} is deprecated in JupyterHub {version}."
" Please use {cls}.{new_name} instead."
).format(
cls=self.__class__.__name__,
old_name=old_name,
new_name=new_name,
version=version,
f"{self.__class__.__name__}.{old_name} is deprecated in JupyterHub {version}."
f" Please use {self.__class__.__name__}.{new_name} instead."
),
DeprecationWarning,
stacklevel=2,
@@ -961,11 +956,9 @@ class LocalAuthenticator(Authenticator):
await maybe_future(self.add_system_user(user))
else:
raise KeyError(
"User {} does not exist on the system."
f"User {user.name} does not exist on the system."
" Set LocalAuthenticator.create_system_users=True"
" to automatically create system users from jupyterhub users.".format(
user.name
)
" to automatically create system users from jupyterhub users."
)
await maybe_future(super().add_user(user))

View File

@@ -121,9 +121,7 @@ def upgrade_if_needed(db_url, backup=True, log=None):
if urlinfo.password:
# avoid logging the database password
urlinfo = urlinfo._replace(
netloc='{}:[redacted]@{}:{}'.format(
urlinfo.username, urlinfo.hostname, urlinfo.port
)
netloc=f'{urlinfo.username}:[redacted]@{urlinfo.hostname}:{urlinfo.port}'
)
db_log_url = urlinfo.geturl()
else:

View File

@@ -372,7 +372,7 @@ class BaseHandler(RequestHandler):
auth_info['auth_state'] = await user.get_auth_state()
return await self.auth_to_user(auth_info, user)
@functools.lru_cache()
@functools.lru_cache
def get_token(self):
"""get token from authorization header"""
token = self.get_auth_token()
@@ -473,7 +473,7 @@ class BaseHandler(RequestHandler):
self.expanded_scopes = scopes.get_scopes_for(self.current_user)
self.parsed_scopes = scopes.parse_scopes(self.expanded_scopes)
@functools.lru_cache()
@functools.lru_cache
def get_scope_filter(self, req_scope):
"""Produce a filter function for req_scope on resources
@@ -981,9 +981,7 @@ class BaseHandler(RequestHandler):
)
err = web.HTTPError(
429,
"Too many users trying to log in right now. Try again in {}.".format(
human_retry_time
),
f"Too many users trying to log in right now. Try again in {human_retry_time}.",
)
# can't call set_header directly here because it gets ignored
# when errors are raised
@@ -1155,8 +1153,7 @@ class BaseHandler(RequestHandler):
raise web.HTTPError(
500,
"Spawner failed to start [status=%s]. The logs for %s may contain details."
% (status, spawner._log_name),
f"Spawner failed to start [status={status}]. The logs for {spawner._log_name} may contain details.",
)
if spawner._waiting_for_response:
@@ -1295,7 +1292,7 @@ class BaseHandler(RequestHandler):
home = url_path_join(self.hub.base_url, 'home')
return (
"You can try restarting your server from the "
"<a href='{home}'>home page</a>.".format(home=home)
f"<a href='{home}'>home page</a>."
)
def get_template(self, name, sync=False):

View File

@@ -163,9 +163,7 @@ class Server(HasTraits):
return f"{self.host}{self.base_url}"
def __repr__(self):
return "{name}(url={url}, bind_url={bind})".format(
name=self.__class__.__name__, url=self.url, bind=self.bind_url
)
return f"{self.__class__.__name__}(url={self.url}, bind_url={self.bind_url})"
def wait_up(self, timeout=10, http=False, ssl_context=None, extra_path=""):
"""Wait for this server to come up"""

View File

@@ -730,7 +730,7 @@ class _Share:
return cls._apply_filter(frozenset(scopes), spawner.user.name, spawner.name)
@staticmethod
@lru_cache()
@lru_cache
def _apply_filter(scopes, owner_name, server_name):
"""
implementation of Share.apply_filter
@@ -1518,11 +1518,9 @@ def check_db_revision(engine):
app_log.debug("database schema version found: %s", alembic_revision)
else:
raise DatabaseSchemaMismatch(
"Found database schema version {found} != {head}. "
f"Found database schema version {alembic_revision} != {head}. "
"Backup your database and run `jupyterhub upgrade-db`"
" to upgrade to the latest schema.".format(
found=alembic_revision, head=head
)
" to upgrade to the latest schema."
)

View File

@@ -337,8 +337,7 @@ class Proxy(LoggingConfigurable):
if spawner.pending and spawner.pending != 'spawn':
raise RuntimeError(
"%s is pending %s, shouldn't be added to the proxy yet!"
% (spawner._log_name, spawner.pending)
f"{spawner._log_name} is pending {spawner.pending}, shouldn't be added to the proxy yet!"
)
await self.add_route(
@@ -941,9 +940,7 @@ class ConfigurableHTTPProxy(Proxy):
# errors.
if e.code >= 500:
self.log.warning(
"api_request to the proxy failed with status code {}, retrying...".format(
e.code
)
f"api_request to the proxy failed with status code {e.code}, retrying..."
)
return False # a falsy return value make exponential_backoff retry
else:

View File

@@ -212,7 +212,7 @@ def _intersect_expanded_scopes(scopes_a, scopes_b, db=None):
scopes_b = frozenset(scopes_b)
# cached lookups for group membership of users and servers
@lru_cache()
@lru_cache
def groups_for_user(username):
"""Get set of group names for a given username"""
# if we need a group lookup, the result is not cacheable
@@ -225,7 +225,7 @@ def _intersect_expanded_scopes(scopes_a, scopes_b, db=None):
)
return {row[0] for row in group_query}
@lru_cache()
@lru_cache
def groups_for_server(server):
"""Get set of group names for a given server"""
username, _, servername = server.partition("/")
@@ -456,7 +456,7 @@ def expand_share_scopes(share):
)
@lru_cache()
@lru_cache
def _expand_self_scope(username):
"""
Users have a metascope 'self' that should be expanded to standard user privileges.

View File

@@ -1194,7 +1194,7 @@ async def test_progress(request, app, no_patience, slow_spawn):
assert evt == {
'progress': 100,
'message': f'Server ready at {url}',
'html_message': 'Server ready at <a href="{0}">{0}</a>'.format(url),
'html_message': f'Server ready at <a href="{url}">{url}</a>',
'url': url,
'ready': True,
}
@@ -1307,7 +1307,7 @@ async def test_progress_ready_hook_async_func_exception(request, app):
db = app.db
name = 'saga'
app_user = add_user(db, app=app, name=name)
html_message = 'Server ready at <a href="{0}">{0}</a>'.format(app_user.url)
html_message = f'Server ready at <a href="{app_user.url}">{app_user.url}</a>'
spawner = app_user.spawner
async def custom_progress_ready_hook(spawner, ready_event):

View File

@@ -85,9 +85,7 @@ async def test_default_server(app, named_servers):
'pending': None,
'ready': True,
'stopped': False,
'progress_url': 'PREFIX/hub/api/users/{}/server/progress'.format(
username
),
'progress_url': f'PREFIX/hub/api/users/{username}/server/progress',
'state': {'pid': 0},
'user_options': {},
}

View File

@@ -82,16 +82,12 @@ class ByteSpecification(Integer):
num = float(value[:-1])
except ValueError:
raise TraitError(
'{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(
val=value
)
f'{value} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'
)
suffix = value[-1]
if suffix not in self.UNIT_SUFFIXES:
raise TraitError(
'{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(
val=value
)
f'{value} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'
)
else:
return int(float(num) * self.UNIT_SUFFIXES[suffix])

View File

@@ -897,9 +897,7 @@ class User:
self.settings['statsd'].incr('spawner.failure.timeout')
else:
self.log.exception(
"Unhandled error starting {user}'s server: {error}".format(
user=self.name, error=e
)
f"Unhandled error starting {self.name}'s server: {e}"
)
self.settings['statsd'].incr('spawner.failure.error')
e.reason = 'error'
@@ -907,9 +905,7 @@ class User:
await self.stop(spawner.name)
except Exception:
self.log.exception(
"Failed to cleanup {user}'s server that failed to start".format(
user=self.name
),
f"Failed to cleanup {self.name}'s server that failed to start",
exc_info=True,
)
# raise original exception
@@ -967,9 +963,7 @@ class User:
await self.stop(spawner.name)
except Exception:
self.log.exception(
"Failed to cleanup {user}'s server that failed to start".format(
user=self.name
),
f"Failed to cleanup {self.name}'s server that failed to start",
exc_info=True,
)
# raise original TimeoutError

View File

@@ -253,9 +253,7 @@ async def wait_for_server(ip, port, timeout=10):
tic = time.perf_counter()
await exponential_backoff(
lambda: can_connect(ip, port),
"Server at {ip}:{port} didn't respond in {timeout} seconds".format(
ip=ip, port=port, timeout=timeout
),
f"Server at {ip}:{port} didn't respond in {timeout} seconds",
timeout=timeout,
)
toc = time.perf_counter()
@@ -301,9 +299,7 @@ async def wait_for_http_server(url, timeout=10, ssl_context=None):
re = await exponential_backoff(
is_reachable,
"Server at {url} didn't respond in {timeout} seconds".format(
url=url, timeout=timeout
),
f"Server at {url} didn't respond in {timeout} seconds",
timeout=timeout,
)
toc = time.perf_counter()
@@ -507,14 +503,12 @@ def print_ps_info(file=sys.stderr):
threadlen = len('threads')
print(
"%s %s %s %s"
% ('%CPU'.ljust(cpulen), 'MEM'.ljust(memlen), 'FDs'.ljust(fdlen), 'threads'),
"{} {} {} {}".format('%CPU'.ljust(cpulen), 'MEM'.ljust(memlen), 'FDs'.ljust(fdlen), 'threads'),
file=file,
)
print(
"%s %s %s %s"
% (
"{} {} {} {}".format(
cpu_s.ljust(cpulen),
mem_s.ljust(memlen),
fd_s.ljust(fdlen),
@@ -788,7 +782,7 @@ _dns_safe = set(string.ascii_letters + string.digits + '-.')
_dns_needs_replace = _dns_safe | {"%"}
@lru_cache()
@lru_cache
def _dns_quote(name):
"""Escape a name for use in a dns label