run ruff via pre-commit

This commit is contained in:
Min RK
2024-03-11 09:39:10 +01:00
parent 25da2c2ad3
commit 52af3abedc
22 changed files with 59 additions and 87 deletions

View File

@@ -7,6 +7,7 @@ bower-lite
Since Bower's on its way out,
stage frontend dependencies from node_modules into components
"""
import json
import os
import shutil

View File

@@ -27,6 +27,7 @@ def clean_dir_hook(spawner):
if os.path.exists(temp_path) and os.path.isdir(temp_path):
shutil.rmtree(temp_path)
c = get_config() # noqa
# attach the hook functions to the spawner

View File

@@ -9,6 +9,7 @@ Example of starting/stopping a server via the JupyterHub API
5. stop server via API
6. wait for server to finish stopping
"""
import json
import logging
import pathlib

View File

@@ -2,6 +2,7 @@
"""
whoami service authentication with the Hub
"""
import json
import os
import secrets

View File

@@ -8,6 +8,7 @@ from jupyterhub.spawner import LocalProcessSpawner
c = get_config() # noqa
class DemoFormSpawner(LocalProcessSpawner):
def _options_form_default(self):
default_env = "YOURNAME=%s\n" % self.user.name

View File

@@ -254,14 +254,15 @@
}
],
"source": [
"from IPython.display import display, HTML\n",
"from IPython.display import HTML, display\n",
"\n",
"full_accept_url = f\"{hub_host}{code_info['accept_url']}\"\n",
"\n",
"display(\n",
" HTML(f\"\"\"\n",
" <a href='{full_accept_url}'>share this link to grant access</a>\n",
" \"\"\")\n",
")\n"
")"
]
},
{
@@ -347,7 +348,9 @@
"from urllib.parse import urlencode\n",
"\n",
"this_notebook_url = server_base_url + \"lab/tree/share-api.ipynb\"\n",
"this_notebook_accept_url = full_accept_url + \"&\" + urlencode({\"next\": this_notebook_url})\n",
"this_notebook_accept_url = (\n",
" full_accept_url + \"&\" + urlencode({\"next\": this_notebook_url})\n",
")\n",
"print(this_notebook_accept_url)\n",
"\n",
"display(\n",
@@ -355,7 +358,7 @@
" share <a href='{this_notebook_accept_url}'>this link</a>\n",
" to grant access and direct users to this notebook\n",
" \"\"\")\n",
")\n"
")"
]
},
{
@@ -497,7 +500,7 @@
"}\n",
"\n",
"\n",
"session.post(share_codes_url, data=json.dumps(options))\n"
"session.post(share_codes_url, data=json.dumps(options))"
]
},
{
@@ -598,7 +601,7 @@
" \"user\": \"shared-with\",\n",
"}\n",
"\n",
"session.patch(shares_url, data=json.dumps(options))\n"
"session.patch(shares_url, data=json.dumps(options))"
]
},
{

View File

@@ -593,10 +593,8 @@ class UserServerAPIHandler(APIHandler):
if named_server_limit_per_user <= len(named_spawners):
raise web.HTTPError(
400,
"User {} already has the maximum of {} named servers."
" One must be deleted before a new server can be created".format(
user_name, named_server_limit_per_user
),
f"User {user_name} already has the maximum of {named_server_limit_per_user} named servers."
" One must be deleted before a new server can be created",
)
spawner = user.get_spawner(server_name, replace_failed=True)
pending = spawner.pending

View File

@@ -1,5 +1,6 @@
#!/usr/bin/env python3
"""The multi-user notebook application"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import asyncio
@@ -24,7 +25,6 @@ from textwrap import dedent
from typing import Optional
from urllib.parse import unquote, urlparse, urlunparse
import tornado.httpserver
import tornado.options
from dateutil.parser import parse as parse_date
@@ -3315,9 +3315,7 @@ class JupyterHub(Application):
config_file_dir = os.path.dirname(os.path.abspath(self.config_file))
if not os.path.isdir(config_file_dir):
self.exit(
"{} does not exist. The destination directory must exist before generating config file.".format(
config_file_dir
)
f"{config_file_dir} does not exist. The destination directory must exist before generating config file."
)
if os.path.exists(self.config_file) and not self.answer_yes:
answer = ''

View File

@@ -196,12 +196,7 @@ class Authenticator(LoggingConfigurable):
# protects backward-compatible config from warnings
# if they set the same value under both names
self.log.warning(
"{cls}.{old} is deprecated in JupyterHub {version}, use {cls}.{new} instead".format(
cls=self.__class__.__name__,
old=old_attr,
new=new_attr,
version=version,
)
f"{self.__class__.__name__}.{old_attr} is deprecated in JupyterHub {version}, use {self.__class__.__name__}.{new_attr} instead"
)
setattr(self, new_attr, change.new)
@@ -377,9 +372,7 @@ class Authenticator(LoggingConfigurable):
break
if has_old_name and not has_new_name:
warnings.warn(
"{0}.{1} should be renamed to {0}.{2} for JupyterHub >= 1.2".format(
cls.__name__, old_name, new_name
),
f"{cls.__name__}.{old_name} should be renamed to {cls.__name__}.{new_name} for JupyterHub >= 1.2",
DeprecationWarning,
)
@@ -399,19 +392,17 @@ class Authenticator(LoggingConfigurable):
):
# adapt to pre-1.0 signature for compatibility
warnings.warn(
"""
{0}.{1} does not support the authentication argument,
added in JupyterHub 1.0. and is renamed to {2} in JupyterHub 1.2.
f"""
{self.__class__.__name__}.{old_name} does not support the authentication argument,
added in JupyterHub 1.0. and is renamed to {new_name} in JupyterHub 1.2.
It should have the signature:
def {2}(self, username, authentication=None):
def {new_name}(self, username, authentication=None):
...
Adapting for compatibility.
""".format(
self.__class__.__name__, old_name, new_name
),
""",
DeprecationWarning,
)

View File

@@ -1519,9 +1519,9 @@ class UserUrlHandler(BaseHandler):
json.dumps(
{
"message": (
"JupyterHub server no longer running at {}."
" Restart the server at {}"
).format(self.request.path[len(self.hub.base_url) - 1 :], spawn_url)
f"JupyterHub server no longer running at {self.request.path[len(self.hub.base_url) - 1 :]}."
f" Restart the server at {spawn_url}"
)
}
)
)

View File

@@ -142,10 +142,8 @@ class SpawnHandler(BaseHandler):
if named_server_limit_per_user <= len(named_spawners):
raise web.HTTPError(
400,
"User {} already has the maximum of {} named servers."
" One must be deleted before a new server can be created".format(
user.name, named_server_limit_per_user
),
f"User {user.name} already has the maximum of {named_server_limit_per_user} named servers."
" One must be deleted before a new server can be created",
)
if not self.allow_named_servers and user.running:
@@ -554,7 +552,6 @@ class TokenPageHandler(BaseHandler):
class AcceptShareHandler(BaseHandler):
def _get_next_url(self, owner, spawner):
"""Get next_url for a given owner/spawner"""
next_url = self.get_argument("next", "")

View File

@@ -202,12 +202,7 @@ class Role(Base):
groups = relationship('Group', secondary='group_role_map', back_populates='roles')
def __repr__(self):
return "<{} {} ({}) - scopes: {}>".format(
self.__class__.__name__,
self.name,
self.description,
self.scopes,
)
return f"<{self.__class__.__name__} {self.name} ({self.description}) - scopes: {self.scopes}>"
@classmethod
def find(cls, db, name):
@@ -365,12 +360,7 @@ class User(Base):
kind = "user"
def __repr__(self):
return "<{cls}({name} {running}/{total} running)>".format(
cls=self.__class__.__name__,
name=self.name,
total=len(self._orm_spawners),
running=sum(bool(s.server) for s in self._orm_spawners),
)
return f"<{self.__class__.__name__}({self.name} {sum(bool(s.server) for s in self._orm_spawners)}/{len(self._orm_spawners)} running)>"
def new_api_token(self, token=None, **kwargs):
"""Create a new API token
@@ -1098,13 +1088,7 @@ class APIToken(Hashed, Base):
# this shouldn't happen
kind = 'owner'
name = 'unknown'
return "<{cls}('{pre}...', {kind}='{name}', client_id={client_id!r})>".format(
cls=self.__class__.__name__,
pre=self.prefix,
kind=kind,
name=name,
client_id=self.client_id,
)
return f"<{self.__class__.__name__}('{self.prefix}...', {kind}='{name}', client_id={self.client_id!r})>"
@classmethod
def find(cls, db, token, *, kind=None):

View File

@@ -686,7 +686,9 @@ class ConfigurableHTTPProxy(Proxy):
cmd = []
proxy_api = 'proxy-api'
proxy_client = 'proxy-client'
api_key = self.app.internal_proxy_certs[proxy_api][
api_key = self.app.internal_proxy_certs[
proxy_api
][
'keyfile'
] # Check content in next test and just patch manulaly or in the config of the file
api_cert = self.app.internal_proxy_certs[proxy_api]['certfile']

View File

@@ -1270,9 +1270,7 @@ def define_custom_scopes(scopes):
},
}
)
""" % indent(
_custom_scope_description, " " * 8
)
""" % indent(_custom_scope_description, " " * 8)
for scope, scope_definition in scopes.items():
if scope in scope_definitions and scope_definitions[scope] != scope_definition:
raise ValueError(

View File

@@ -82,7 +82,10 @@ def _disable_user_config(serverapp):
assert serverapp.config_file_paths == config_file_paths
# patch jupyter_path to exclude $HOME
global _original_jupyter_paths, _jupyter_paths_without_home, _original_jupyter_config_dir
global \
_original_jupyter_paths, \
_jupyter_paths_without_home, \
_original_jupyter_config_dir
_original_jupyter_paths = paths.jupyter_path()
_jupyter_paths_without_home = list(_exclude_home(_original_jupyter_paths))

View File

@@ -6,6 +6,7 @@ Meant to be compatible with jupyter_server and classic notebook
Use make_singleuser_app to create a compatible Application class
with JupyterHub authentication mixins enabled.
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import asyncio

View File

@@ -172,9 +172,7 @@ async def test_create_named_server(
'pending': None,
'ready': True,
'stopped': False,
'progress_url': 'PREFIX/hub/api/users/{}/servers/{}/progress'.format(
username, escapedname
),
'progress_url': f'PREFIX/hub/api/users/{username}/servers/{escapedname}/progress',
'state': {'pid': 0},
'user_options': {},
}

View File

@@ -73,13 +73,13 @@ def test_user(db):
def test_user_escaping(db):
orm_user = orm.User(name='company\\user@company.com,\"quoted\"')
orm_user = orm.User(name='company\\user@company.com,"quoted"')
db.add(orm_user)
db.commit()
user = User(orm_user)
assert user.name == 'company\\user@company.com,\"quoted\"'
assert user.name == 'company\\user@company.com,"quoted"'
assert user.escaped_name == 'company%5Cuser@company.com%2C%22quoted%22'
assert user.json_escaped_name == 'company\\\\user@company.com,\\\"quoted\\\"'
assert user.json_escaped_name == 'company\\\\user@company.com,\\"quoted\\"'
def test_tokens(db):

View File

@@ -10,9 +10,8 @@ import pytest
from traitlets import TraitError
from traitlets.config import Config
from ..utils import random_port
from ..utils import random_port, wait_for_http_server
from ..utils import url_path_join as ujoin
from ..utils import wait_for_http_server
from .mocking import MockHub
from .test_api import add_user, api_request
from .utils import skip_if_ssl

View File

@@ -954,9 +954,7 @@ class User:
else:
e.reason = 'error'
self.log.exception(
"Unhandled error waiting for {user}'s server to show up at {url}: {error}".format(
user=self.name, url=server.url, error=e
)
f"Unhandled error waiting for {self.name}'s server to show up at {server.url}: {e}"
)
self.settings['statsd'].incr('spawner.failure.http_error')
try:

View File

@@ -503,17 +503,14 @@ def print_ps_info(file=sys.stderr):
threadlen = len('threads')
print(
"{} {} {} {}".format('%CPU'.ljust(cpulen), 'MEM'.ljust(memlen), 'FDs'.ljust(fdlen), 'threads'),
"{} {} {} {}".format(
'%CPU'.ljust(cpulen), 'MEM'.ljust(memlen), 'FDs'.ljust(fdlen), 'threads'
),
file=file,
)
print(
"{} {} {} {}".format(
cpu_s.ljust(cpulen),
mem_s.ljust(memlen),
fd_s.ljust(fdlen),
str(p.num_threads()).ljust(7),
),
f"{cpu_s.ljust(cpulen)} {mem_s.ljust(memlen)} {fd_s.ljust(fdlen)} {str(p.num_threads()).ljust(7)}",
file=file,
)