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, Since Bower's on its way out,
stage frontend dependencies from node_modules into components stage frontend dependencies from node_modules into components
""" """
import json import json
import os import os
import shutil 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): if os.path.exists(temp_path) and os.path.isdir(temp_path):
shutil.rmtree(temp_path) shutil.rmtree(temp_path)
c = get_config() # noqa c = get_config() # noqa
# attach the hook functions to the spawner # 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 5. stop server via API
6. wait for server to finish stopping 6. wait for server to finish stopping
""" """
import json import json
import logging import logging
import pathlib import pathlib

View File

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

View File

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

View File

@@ -254,14 +254,15 @@
} }
], ],
"source": [ "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", "full_accept_url = f\"{hub_host}{code_info['accept_url']}\"\n",
"\n", "\n",
"display(\n", "display(\n",
" HTML(f\"\"\"\n", " HTML(f\"\"\"\n",
" <a href='{full_accept_url}'>share this link to grant access</a>\n", " <a href='{full_accept_url}'>share this link to grant access</a>\n",
" \"\"\")\n", " \"\"\")\n",
")\n" ")"
] ]
}, },
{ {
@@ -347,7 +348,9 @@
"from urllib.parse import urlencode\n", "from urllib.parse import urlencode\n",
"\n", "\n",
"this_notebook_url = server_base_url + \"lab/tree/share-api.ipynb\"\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", "print(this_notebook_accept_url)\n",
"\n", "\n",
"display(\n", "display(\n",
@@ -355,7 +358,7 @@
" share <a href='{this_notebook_accept_url}'>this link</a>\n", " share <a href='{this_notebook_accept_url}'>this link</a>\n",
" to grant access and direct users to this notebook\n", " to grant access and direct users to this notebook\n",
" \"\"\")\n", " \"\"\")\n",
")\n" ")"
] ]
}, },
{ {
@@ -488,16 +491,16 @@
"import json\n", "import json\n",
"\n", "\n",
"options = {\n", "options = {\n",
" \"scopes\": [\n", " \"scopes\": [\n",
" f\"access:servers!server={user_server}\", # access the server (default)\n", " f\"access:servers!server={user_server}\", # access the server (default)\n",
" f\"servers!server={user_server}\", # start/stop the server\n", " f\"servers!server={user_server}\", # start/stop the server\n",
" f\"shares!server={user_server}\", # further share the server with others\n", " f\"shares!server={user_server}\", # further share the server with others\n",
" ],\n", " ],\n",
" \"expires_in\": 3600, # code expires in one hour\n", " \"expires_in\": 3600, # code expires in one hour\n",
"}\n", "}\n",
"\n", "\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", " \"user\": \"shared-with\",\n",
"}\n", "}\n",
"\n", "\n",
"session.patch(shares_url, data=json.dumps(options))\n" "session.patch(shares_url, data=json.dumps(options))"
] ]
}, },
{ {

View File

@@ -1,7 +1,7 @@
"""base revision for 0.5 """base revision for 0.5
Revision ID: 19c0846f6344 Revision ID: 19c0846f6344
Revises: Revises:
Create Date: 2016-04-11 16:05:34.873288 Create Date: 2016-04-11 16:05:34.873288
""" """

View File

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

View File

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

View File

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

View File

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

View File

@@ -142,10 +142,8 @@ class SpawnHandler(BaseHandler):
if named_server_limit_per_user <= len(named_spawners): if named_server_limit_per_user <= len(named_spawners):
raise web.HTTPError( raise web.HTTPError(
400, 400,
"User {} already has the maximum of {} named servers." 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".format( " One must be deleted before a new server can be created",
user.name, named_server_limit_per_user
),
) )
if not self.allow_named_servers and user.running: if not self.allow_named_servers and user.running:
@@ -554,7 +552,6 @@ class TokenPageHandler(BaseHandler):
class AcceptShareHandler(BaseHandler): class AcceptShareHandler(BaseHandler):
def _get_next_url(self, owner, spawner): def _get_next_url(self, owner, spawner):
"""Get next_url for a given owner/spawner""" """Get next_url for a given owner/spawner"""
next_url = self.get_argument("next", "") 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') groups = relationship('Group', secondary='group_role_map', back_populates='roles')
def __repr__(self): def __repr__(self):
return "<{} {} ({}) - scopes: {}>".format( return f"<{self.__class__.__name__} {self.name} ({self.description}) - scopes: {self.scopes}>"
self.__class__.__name__,
self.name,
self.description,
self.scopes,
)
@classmethod @classmethod
def find(cls, db, name): def find(cls, db, name):
@@ -365,12 +360,7 @@ class User(Base):
kind = "user" kind = "user"
def __repr__(self): def __repr__(self):
return "<{cls}({name} {running}/{total} running)>".format( return f"<{self.__class__.__name__}({self.name} {sum(bool(s.server) for s in self._orm_spawners)}/{len(self._orm_spawners)} running)>"
cls=self.__class__.__name__,
name=self.name,
total=len(self._orm_spawners),
running=sum(bool(s.server) for s in self._orm_spawners),
)
def new_api_token(self, token=None, **kwargs): def new_api_token(self, token=None, **kwargs):
"""Create a new API token """Create a new API token
@@ -1098,13 +1088,7 @@ class APIToken(Hashed, Base):
# this shouldn't happen # this shouldn't happen
kind = 'owner' kind = 'owner'
name = 'unknown' name = 'unknown'
return "<{cls}('{pre}...', {kind}='{name}', client_id={client_id!r})>".format( return f"<{self.__class__.__name__}('{self.prefix}...', {kind}='{name}', client_id={self.client_id!r})>"
cls=self.__class__.__name__,
pre=self.prefix,
kind=kind,
name=name,
client_id=self.client_id,
)
@classmethod @classmethod
def find(cls, db, token, *, kind=None): def find(cls, db, token, *, kind=None):

View File

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

View File

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

View File

@@ -82,7 +82,10 @@ def _disable_user_config(serverapp):
assert serverapp.config_file_paths == config_file_paths assert serverapp.config_file_paths == config_file_paths
# patch jupyter_path to exclude $HOME # 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() _original_jupyter_paths = paths.jupyter_path()
_jupyter_paths_without_home = list(_exclude_home(_original_jupyter_paths)) _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 Use make_singleuser_app to create a compatible Application class
with JupyterHub authentication mixins enabled. with JupyterHub authentication mixins enabled.
""" """
# Copyright (c) Jupyter Development Team. # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License. # Distributed under the terms of the Modified BSD License.
import asyncio import asyncio

View File

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

View File

@@ -73,13 +73,13 @@ def test_user(db):
def test_user_escaping(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.add(orm_user)
db.commit() db.commit()
user = User(orm_user) 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.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): def test_tokens(db):

View File

@@ -10,9 +10,8 @@ import pytest
from traitlets import TraitError from traitlets import TraitError
from traitlets.config import Config 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 url_path_join as ujoin
from ..utils import wait_for_http_server
from .mocking import MockHub from .mocking import MockHub
from .test_api import add_user, api_request from .test_api import add_user, api_request
from .utils import skip_if_ssl from .utils import skip_if_ssl

View File

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

View File

@@ -503,17 +503,14 @@ def print_ps_info(file=sys.stderr):
threadlen = len('threads') threadlen = len('threads')
print( 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, file=file,
) )
print( print(
"{} {} {} {}".format( f"{cpu_s.ljust(cpulen)} {mem_s.ljust(memlen)} {fd_s.ljust(fdlen)} {str(p.num_threads()).ljust(7)}",
cpu_s.ljust(cpulen),
mem_s.ljust(memlen),
fd_s.ljust(fdlen),
str(p.num_threads()).ljust(7),
),
file=file, file=file,
) )