Skip to content

Commit

Permalink
satisfy updated ruff rules
Browse files Browse the repository at this point in the history
mostly f-strings, manual fixes
  • Loading branch information
minrk committed Dec 3, 2024
1 parent def928f commit a2877c7
Show file tree
Hide file tree
Showing 16 changed files with 44 additions and 45 deletions.
1 change: 0 additions & 1 deletion examples/service-whoami-flask/whoami-flask.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from functools import wraps

from flask import Flask, Response, make_response, redirect, request, session

from jupyterhub.services.auth import HubOAuth

prefix = os.environ.get('JUPYTERHUB_SERVICE_PREFIX', '/')
Expand Down
2 changes: 1 addition & 1 deletion jupyterhub/apihandlers/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ async def post(self):
raise web.HTTPError(400, msg)

if not to_create:
raise web.HTTPError(409, "All %i users already exist" % len(usernames))
raise web.HTTPError(409, f"All {len(usernames)} users already exist")

created = []
for name in to_create:
Expand Down
2 changes: 1 addition & 1 deletion jupyterhub/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3320,7 +3320,7 @@ def write_pid_file(self):
if self.pid_file:
self.log.debug("Writing PID %i to %s", pid, self.pid_file)
with open(self.pid_file, 'w') as f:
f.write('%i' % pid)
f.write(str(pid))

@catch_config_error
async def initialize(self, *args, **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion jupyterhub/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -1225,7 +1225,7 @@ def add_system_user(self, user):
cmd = [arg.replace('USERNAME', name) for arg in self.add_user_cmd]
try:
uid = self.uids[name]
cmd += ['--uid', '%d' % uid]
cmd += ['--uid', str(uid)]
except KeyError:
self.log.debug(f"No UID for user {name}")
cmd += [name]
Expand Down
10 changes: 6 additions & 4 deletions jupyterhub/handlers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1061,10 +1061,12 @@ async def spawn_single_user(self, user, server_name='', options=None):
# round suggestion to nicer human value (nearest 10 seconds or minute)
if retry_time <= 90:
# round human seconds up to nearest 10
human_retry_time = "%i0 seconds" % math.ceil(retry_time / 10.0)
delay = math.ceil(retry_time / 10.0)
human_retry_time = f"{delay}0 seconds"
else:
# round number of minutes
human_retry_time = "%i minutes" % round(retry_time / 60.0)
delay = round(retry_time / 60.0)
human_retry_time = f"{delay} minutes"

self.log.warning(
'%s pending spawns, throttling. Suggested retry in %s seconds.',
Expand Down Expand Up @@ -1099,12 +1101,12 @@ async def spawn_single_user(self, user, server_name='', options=None):
self.log.debug(
"%i%s concurrent spawns",
spawn_pending_count,
'/%i' % concurrent_spawn_limit if concurrent_spawn_limit else '',
f'/{concurrent_spawn_limit}' if concurrent_spawn_limit else '',
)
self.log.debug(
"%i%s active servers",
active_count,
'/%i' % active_server_limit if active_server_limit else '',
f'/{active_server_limit}' if active_server_limit else '',
)

spawner = user.spawners[server_name]
Expand Down
2 changes: 1 addition & 1 deletion jupyterhub/orm.py
Original file line number Diff line number Diff line change
Expand Up @@ -1050,7 +1050,7 @@ class APIToken(Hashed, Base):

@property
def api_id(self):
return 'a%i' % self.id
return f"a{self.id}"

@property
def owner(self):
Expand Down
7 changes: 4 additions & 3 deletions jupyterhub/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,14 +358,15 @@ async def _mockservice(request, app, name, external=False, url=False):
(as opposed to headless, API-only).
"""
spec = {'name': name, 'command': mockservice_cmd, 'admin': True}
port = random_port()
if url:
if app.internal_ssl:
spec['url'] = 'https://127.0.0.1:%i' % random_port()
spec['url'] = f'https://127.0.0.1:{port}'
else:
spec['url'] = 'http://127.0.0.1:%i' % random_port()
spec['url'] = f'http://127.0.0.1:{port}'

if external:
spec['oauth_redirect_uri'] = 'http://127.0.0.1:%i' % random_port()
spec['oauth_redirect_uri'] = f'http://127.0.0.1:{port}'

event_loop = asyncio.get_running_loop()

Expand Down
2 changes: 1 addition & 1 deletion jupyterhub/tests/mocking.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ def _default_bind_url(self):
port = urlparse(self.subdomain_host).port
else:
port = random_port()
return 'http://127.0.0.1:%i/@/space%%20word/' % (port,)
return f'http://127.0.0.1:{port}/@/space%20word/'

@default('ip')
def _ip_default(self):
Expand Down
4 changes: 2 additions & 2 deletions jupyterhub/tests/test_crypto.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from .. import crypto
from ..crypto import decrypt, encrypt

keys = [('%i' % i).encode('ascii') * 32 for i in range(3)]
keys = [str(i).encode('ascii') * 32 for i in range(3)]
hex_keys = [b2a_hex(key).decode('ascii') for key in keys]
b64_keys = [b2a_base64(key).decode('ascii').strip() for key in keys]

Expand Down Expand Up @@ -36,7 +36,7 @@ def test_env_constructor(key_env, keys):
"key",
[
'a' * 44, # base64, not 32 bytes
('%44s' % 'notbase64'), # not base64
f"{'notbase64':44}", # not base64
b'x' * 64, # not hex
b'short', # not 32 bytes
],
Expand Down
12 changes: 6 additions & 6 deletions jupyterhub/tests/test_orm.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,19 @@ def test_server(db):

# test wrapper
server = objects.Server(orm_server=server)
assert server.host == 'http://%s:%i' % (socket.gethostname(), server.port)
assert server.host == f'http://{socket.gethostname()}:{server.port}'
assert server.url == server.host + '/'
assert server.bind_url == 'http://*:%i/' % server.port
assert server.bind_url == f'http://*:{server.port}/'
server.ip = '127.0.0.1'
assert server.host == 'http://127.0.0.1:%i' % server.port
assert server.host == f'http://127.0.0.1:{server.port}'
assert server.url == server.host + '/'

server.connect_ip = 'hub'
assert server.host == 'http://hub:%i' % server.port
assert server.host == f'http://hub:{server.port}'
assert server.url == server.host + '/'

server.connect_url = 'http://hub-url:%i/connect' % server.port
assert server.host == 'http://hub-url:%i' % server.port
server.connect_url = f'http://hub-url:{server.port}/connect'
assert server.host == f'http://hub-url:{server.port}'

server.bind_url = 'http://127.0.0.1/'
assert server.port == 80
Expand Down
2 changes: 1 addition & 1 deletion jupyterhub/tests/test_pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -1060,7 +1060,7 @@ async def test_oauth_token_page(app):

@pytest.mark.parametrize("error_status", [503, 404])
async def test_proxy_error(app, error_status):
r = await get_page('/error/%i' % error_status, app)
r = await get_page(f'/error/{error_status}', app)
assert r.status_code == 200


Expand Down
6 changes: 3 additions & 3 deletions jupyterhub/tests/test_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async def test_external_proxy(request):
proxy_port = random_port()
cfg = Config()
cfg.ConfigurableHTTPProxy.auth_token = auth_token
cfg.ConfigurableHTTPProxy.api_url = 'http://%s:%i' % (proxy_ip, proxy_port)
cfg.ConfigurableHTTPProxy.api_url = f'http://{proxy_ip}:{proxy_port}'
cfg.ConfigurableHTTPProxy.should_start = False

app = MockHub.instance(config=cfg)
Expand Down Expand Up @@ -76,7 +76,7 @@ def _cleanup_proxy():
request.addfinalizer(_cleanup_proxy)

def wait_for_proxy():
return wait_for_http_server('http://%s:%i' % (proxy_ip, proxy_port))
return wait_for_http_server(f'http://{proxy_ip}:{proxy_port}')

await wait_for_proxy()

Expand Down Expand Up @@ -141,7 +141,7 @@ def wait_for_proxy():
'--api-port',
str(proxy_port),
'--default-target',
'http://%s:%i' % (app.hub_ip, app.hub_port),
f'http://{app.hub_ip}:{app.hub_port}',
]
if app.subdomain_host:
cmd.append('--host-routing')
Expand Down
2 changes: 1 addition & 1 deletion jupyterhub/tests/test_services.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ async def external_service(app, name='mockservice'):
'JUPYTERHUB_API_TOKEN': hexlify(os.urandom(5)),
'JUPYTERHUB_SERVICE_NAME': name,
'JUPYTERHUB_API_URL': url_path_join(app.hub.url, 'api/'),
'JUPYTERHUB_SERVICE_URL': 'http://127.0.0.1:%i' % random_port(),
'JUPYTERHUB_SERVICE_URL': f'http://127.0.0.1:{random_port()}',
}
proc = Popen(mockservice_cmd, env=env)
try:
Expand Down
2 changes: 1 addition & 1 deletion jupyterhub/tests/test_spawner.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ async def test_shell_cmd(db, tmpdir, request):
s.server.port = port
db.commit()
await wait_for_spawner(s)
r = await async_requests.get('http://%s:%i/env' % (ip, port))
r = await async_requests.get(f'http://{ip}:{port}/env')
r.raise_for_status()
env = r.json()
assert env['TESTVAR'] == 'foo'
Expand Down
19 changes: 8 additions & 11 deletions jupyterhub/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -920,19 +920,16 @@ async def spawn(self, server_name='', options=None, handler=None):
await asyncio.wait_for(f, timeout=spawner.start_timeout)
url = f.result()
if url:
# get ip, port info from return value of start()
if isinstance(url, str):
# >= 0.9 can return a full URL string
pass
else:
# >= 0.7 returns (ip, port)
# get url from return value of start()
if not isinstance(url, str):
# older Spawners return (ip, port)
proto = 'https' if self.settings['internal_ssl'] else 'http'

ip, port = url
# check if spawner returned an IPv6 address
if ':' in url[0]:
url = '%s://[%s]:%i' % ((proto,) + url)
else:
url = '%s://%s:%i' % ((proto,) + url)
if ':' in ip:
# ipv6 needs [::] in url
ip = f'[{ip}]'
url = f'{proto}://{ip}:{int(port)}'
urlinfo = urlparse(url)
server.proto = urlinfo.scheme
server.ip = urlinfo.hostname
Expand Down
14 changes: 7 additions & 7 deletions jupyterhub/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,20 +502,20 @@ def print_ps_info(file=sys.stderr):
# format CPU percentage
cpu = p.cpu_percent(0.1)
if cpu >= 10:
cpu_s = "%i" % cpu
cpu_s = str(int(cpu))
else:
cpu_s = f"{cpu:.1f}"

# format memory (only resident set)
rss = p.memory_info().rss
if rss >= 1e9:
mem_s = '%.1fG' % (rss / 1e9)
mem_s = f'{rss / 1e9:.1f}G'
elif rss >= 1e7:
mem_s = '%.0fM' % (rss / 1e6)
mem_s = f'{rss / 1e6:.0f}M'
elif rss >= 1e6:
mem_s = '%.1fM' % (rss / 1e6)
mem_s = f'{rss / 1e6:.1f}M'
else:
mem_s = '%.0fk' % (rss / 1e3)
mem_s = f'{rss / 1e3:.0f}k'

# left-justify and shrink-to-fit columns
cpulen = max(len(cpu_s), 4)
Expand Down Expand Up @@ -560,7 +560,7 @@ def print_stacks(file=sys.stderr):

from .log import coroutine_frames

print("Active threads: %i" % threading.active_count(), file=file)
print(f"Active threads: {threading.active_count()}", file=file)
for thread in threading.enumerate():
print(f"Thread {thread.name}:", end='', file=file)
frame = sys._current_frames()[thread.ident]
Expand Down Expand Up @@ -592,7 +592,7 @@ def print_stacks(file=sys.stderr):
# coroutines to native `async def`
tasks = asyncio_all_tasks()
if tasks:
print("AsyncIO tasks: %i" % len(tasks))
print(f"AsyncIO tasks: {len(tasks)}")
for task in tasks:
task.print_stack(file=file)

Expand Down

0 comments on commit a2877c7

Please sign in to comment.