Skip to content

Commit

Permalink
[pre-commit.ci] pre-commit autoupdate (#1322)
Browse files Browse the repository at this point in the history
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Steven Silvester <steven.silvester@ieee.org>
  • Loading branch information
pre-commit-ci[bot] and blink1073 committed Sep 5, 2023
1 parent a7b033d commit 1cb4116
Show file tree
Hide file tree
Showing 18 changed files with 54 additions and 86 deletions.
8 changes: 4 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,22 @@ repos:
- id: trailing-whitespace

- repo: https://github.com/python-jsonschema/check-jsonschema
rev: 0.23.2
rev: 0.26.3
hooks:
- id: check-github-workflows

- repo: https://github.com/executablebooks/mdformat
rev: 0.7.16
rev: 0.7.17
hooks:
- id: mdformat

- repo: https://github.com/psf/black
rev: 23.3.0
rev: 23.7.0
hooks:
- id: black

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.276
rev: v0.0.287
hooks:
- id: ruff
args: ["--fix"]
5 changes: 1 addition & 4 deletions jupyter_server/base/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,10 +403,7 @@ def set_attachment_header(self, filename):
escaped_filename = url_escape(filename)
self.set_header(
"Content-Disposition",
"attachment;"
" filename*=utf-8''{utf8}".format(
utf8=escaped_filename,
),
f"attachment; filename*=utf-8''{escaped_filename}",
)

def get_origin(self):
Expand Down
5 changes: 1 addition & 4 deletions jupyter_server/extension/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,10 +608,7 @@ def launch_instance(cls, argv=None, **kwargs):

# Log if extension is blocking other extensions from loading.
if not cls.load_other_extensions:
serverapp.log.info(
"{ext_name} is running without loading "
"other extensions.".format(ext_name=cls.name)
)
serverapp.log.info(f"{cls.name} is running without loading other extensions.")
# Start the server.
try:
serverapp.start()
Expand Down
12 changes: 6 additions & 6 deletions jupyter_server/extension/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ def get_loader(obj, logger=None):

warnings.warn(
"A `_load_jupyter_server_extension` function was not "
"found in {name!s}. Instead, a `load_jupyter_server_extension` "
f"found in {obj!s}. Instead, a `load_jupyter_server_extension` "
"function was found and will be used for now. This function "
"name will be deprecated in future releases "
"of Jupyter Server.".format(name=obj),
"of Jupyter Server.",
DeprecationWarning,
stacklevel=2,
)
Expand Down Expand Up @@ -91,10 +91,10 @@ def get_metadata(package_name, logger=None):
if logger:
logger.warning(
"A `_jupyter_server_extension_points` function was not "
"found in {name}. Instead, a `_jupyter_server_extension_paths` "
f"found in {package_name}. Instead, a `_jupyter_server_extension_paths` "
"function was found and will be used for now. This function "
"name will be deprecated in future releases "
"of Jupyter Server.".format(name=package_name)
"of Jupyter Server."
)
return module, extension_points
except AttributeError:
Expand All @@ -105,9 +105,9 @@ def get_metadata(package_name, logger=None):
if logger:
logger.debug(
"A `_jupyter_server_extension_points` function was "
"not found in {name}, so Jupyter Server will look "
f"not found in {package_name}, so Jupyter Server will look "
"for extension points in the extension pacakge's "
"root.".format(name=package_name)
"root."
)
return module, [{"module": package_name, "name": package_name}]

Expand Down
4 changes: 1 addition & 3 deletions jupyter_server/gateway/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,7 @@ def handle_outgoing_message(self, incoming_msg: str, *args: Any) -> None:
json_decode(utf8(incoming_msg))
)
self.log.debug(
"Notebook client closed websocket connection - message dropped: {}".format(
msg_summary
)
f"Notebook client closed websocket connection - message dropped: {msg_summary}"
)

def handle_incoming_message(self, message: str) -> None:
Expand Down
13 changes: 3 additions & 10 deletions jupyter_server/gateway/gateway_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,15 +526,8 @@ def _deprecated_trait(self, change):
# protects backward-compatible config from warnings
# if they set the same value under both names
self.log.warning(
(
"{cls}.{old} is deprecated in jupyter_server "
"{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 jupyter_server "
f"{version}, use {self.__class__.__name__}.{new_attr} instead"
)
setattr(self, new_attr, change.new)

Expand Down Expand Up @@ -578,7 +571,7 @@ def init_connection_args(self):
os.environ["KERNEL_LAUNCH_TIMEOUT"] = str(GatewayClient.KERNEL_LAUNCH_TIMEOUT)

self._connection_args["headers"] = json.loads(self.headers)
if self.auth_header_key not in self._connection_args["headers"].keys():
if self.auth_header_key not in self._connection_args["headers"]:
self._connection_args["headers"].update(
{f"{self.auth_header_key}": f"{self.auth_scheme} {self.auth_token}"}
)
Expand Down
4 changes: 1 addition & 3 deletions jupyter_server/gateway/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,7 @@ def write_message(self, message, binary=False):
elif self.log.isEnabledFor(logging.DEBUG):
msg_summary = WebSocketChannelsHandler._get_message_summary(json_decode(utf8(message)))
self.log.debug(
"Notebook client closed websocket connection - message dropped: {}".format(
msg_summary
)
f"Notebook client closed websocket connection - message dropped: {msg_summary}"
)

def on_close(self):
Expand Down
8 changes: 4 additions & 4 deletions jupyter_server/gateway/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ async def get_kernel_spec(self, kernel_name, **kwargs):
try:
response = await gateway_request(kernel_spec_url, method="GET")
except web.HTTPError as error:
if error.status_code == 404: # noqa[PLR2004]
if error.status_code == 404: # noqa: PLR2004
# Convert not found to KeyError since that's what the Notebook handler expects
# message is not used, but might as well make it useful for troubleshooting
msg = f"kernelspec {kernel_name} not found on Gateway server at: {GatewayClient.instance().url}"
Expand Down Expand Up @@ -336,7 +336,7 @@ async def get_kernel_spec_resource(self, kernel_name, path):
try:
response = await gateway_request(kernel_spec_resource_url, method="GET")
except web.HTTPError as error:
if error.status_code == 404: # noqa[PLR2004]
if error.status_code == 404: # noqa: PLR2004
kernel_spec_resource = None
else:
raise
Expand Down Expand Up @@ -433,7 +433,7 @@ async def refresh_model(self, model=None):
response = await gateway_request(self.kernel_url, method="GET")

except web.HTTPError as error:
if error.status_code == 404: # noqa[PLR2004]
if error.status_code == 404: # noqa: PLR2004
self.log.warning("Kernel not found at: %s" % self.kernel_url)
model = None
else:
Expand Down Expand Up @@ -527,7 +527,7 @@ async def shutdown_kernel(self, now=False, restart=False):
response = await gateway_request(self.kernel_url, method="DELETE")
self.log.debug("Shutdown kernel response: %d %s", response.code, response.reason)
except web.HTTPError as error:
if error.status_code == 404: # noqa[PLR2004]
if error.status_code == 404: # noqa: PLR2004
self.log.debug("Shutdown kernel response: kernel not found (ignored)")
else:
raise
Expand Down
10 changes: 5 additions & 5 deletions jupyter_server/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,12 @@ def log_request(handler):
except AttributeError:
logger = access_log

if status < 300 or status == 304: # noqa[PLR2004]
if status < 300 or status == 304: # noqa: PLR2004
# Successes (or 304 FOUND) are debug-level
log_method = logger.debug
elif status < 400: # noqa[PLR2004]
elif status < 400: # noqa: PLR2004
log_method = logger.info
elif status < 500: # noqa[PLR2004]
elif status < 500: # noqa: PLR2004
log_method = logger.warning
else:
log_method = logger.error
Expand All @@ -84,11 +84,11 @@ def log_request(handler):
ns["username"] = username

msg = "{status} {method} {uri} ({username}@{ip}) {request_time:.2f}ms"
if status >= 400: # noqa[PLR2004]
if status >= 400: # noqa: PLR2004
# log bad referers
ns["referer"] = _scrub_uri(request.headers.get("Referer", "None"))
msg = msg + " referer={referer}"
if status >= 500 and status != 502: # noqa[PLR2004]
if status >= 500 and status != 502: # noqa: PLR2004
# Log a subset of the headers if it caused an error.
headers = {}
for header in ["Host", "Accept", "Referer", "User-Agent"]:
Expand Down
12 changes: 3 additions & 9 deletions jupyter_server/serverapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def init_settings(
jenv_opt: dict = {"autoescape": True}
jenv_opt.update(jinja_env_options if jinja_env_options else {})

env = Environment( # noqa[S701]
env = Environment( # noqa: S701
loader=FileSystemLoader(template_path), extensions=["jinja2.ext.i18n"], **jenv_opt
)
sys_info = get_sys_info()
Expand Down Expand Up @@ -2134,9 +2134,7 @@ def init_resources(self):
if hard < soft:
hard = soft
self.log.debug(
"Raising open file limit: soft {}->{}; hard {}->{}".format(
old_soft, soft, old_hard, hard
)
f"Raising open file limit: soft {old_soft}->{soft}; hard {old_hard}->{hard}"
)
resource.setrlimit(resource.RLIMIT_NOFILE, (soft, hard))

Expand Down Expand Up @@ -2631,11 +2629,7 @@ def running_server_info(self, kernel_count=True):
info += kernel_msg % n_kernels
info += "\n"
# Format the info so that the URL fits on a single line in 80 char display
info += _i18n(
"Jupyter Server {version} is running at:\n{url}".format(
version=ServerApp.version, url=self.display_url
)
)
info += _i18n(f"Jupyter Server {ServerApp.version} is running at:\n{self.display_url}")
if self.gateway_config.gateway_enabled:
info += (
_i18n("\nKernels will be managed by the Gateway server running at:\n%s")
Expand Down
6 changes: 1 addition & 5 deletions jupyter_server/services/contents/filecheckpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,7 @@ def checkpoint_path(self, checkpoint_id, path):
parent, name = ("/" + path).rsplit("/", 1)
parent = parent.strip("/")
basename, ext = os.path.splitext(name)
filename = "{name}-{checkpoint_id}{ext}".format(
name=basename,
checkpoint_id=checkpoint_id,
ext=ext,
)
filename = f"{basename}-{checkpoint_id}{ext}"
os_path = self._get_os_path(path=parent)
cp_dir = os.path.join(os_path, self.checkpoint_dir)
with self.perm_to_403():
Expand Down
16 changes: 10 additions & 6 deletions jupyter_server/services/contents/filemanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,10 +678,12 @@ def _get_dir_size(self, path="."):
try:
if platform.system() == "Darwin":
# retuns the size of the folder in KB
result = subprocess.run(["du", "-sk", path], capture_output=True).stdout.split()
result = subprocess.run(
["du", "-sk", path], capture_output=True, check=True
).stdout.split()
else:
result = subprocess.run(
["du", "-s", "--block-size=1", path], capture_output=True
["du", "-s", "--block-size=1", path], capture_output=True, check=True
).stdout.split()

self.log.info(f"current status of du command {result}")
Expand All @@ -704,7 +706,7 @@ def _human_readable_size(self, size):
units = ["Bytes", "KB", "MB", "GB", "TB", "PB"]
order = int(math.log2(size) / 10) if size else 0

return "{:.4g} {}".format(size / (1 << (order * 10)), units[order])
return f"{size / (1 << (order * 10)):.4g} {units[order]}"


class AsyncFileContentsManager(FileContentsManager, AsyncFileManagerMixin, AsyncContentsManager):
Expand Down Expand Up @@ -1137,10 +1139,12 @@ async def _get_dir_size(self, path: str = ".") -> str:
try:
if platform.system() == "Darwin":
# retuns the size of the folder in KB
result = subprocess.run(["du", "-sk", path], capture_output=True).stdout.split()
result = subprocess.run(
["du", "-sk", path], capture_output=True, check=True
).stdout.split()
else:
result = subprocess.run(
["du", "-s", "--block-size=1", path], capture_output=True
["du", "-s", "--block-size=1", path], capture_output=True, check=True
).stdout.split()

self.log.info(f"current status of du command {result}")
Expand All @@ -1163,4 +1167,4 @@ async def _human_readable_size(self, size: int) -> str:
units = ["Bytes", "KB", "MB", "GB", "TB", "PB"]
order = int(math.log2(size) / 10) if size else 0

return "{:.4g} {}".format(size / (1 << (order * 10)), units[order])
return f"{size / (1 << (order * 10)):.4g} {units[order]}"
8 changes: 2 additions & 6 deletions jupyter_server/services/contents/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,9 +540,7 @@ def increment_filename(self, filename, path="", insert=""):

for i in itertools.count():
insert_i = f"{insert}{i}" if i else ""
name = "{basename}{insert}{suffix}".format(
basename=basename, insert=insert_i, suffix=suffix
)
name = f"{basename}{insert_i}{suffix}"
if not self.exists(f"{path}/{name}"):
break
return name
Expand Down Expand Up @@ -929,9 +927,7 @@ async def increment_filename(self, filename, path="", insert=""):

for i in itertools.count():
insert_i = f"{insert}{i}" if i else ""
name = "{basename}{insert}{suffix}".format(
basename=basename, insert=insert_i, suffix=suffix
)
name = f"{basename}{insert_i}{suffix}"
file_exists = await ensure_async(self.exists(f"{path}/{name}"))
if not file_exists:
break
Expand Down
20 changes: 8 additions & 12 deletions jupyter_server/services/kernels/connection/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -703,19 +703,17 @@ def _limit_rate(self, channel, msg, msg_list):
)
self.write_stderr(
dedent(
"""\
f"""\
IOPub message rate exceeded.
The Jupyter server will temporarily stop sending output
to the client in order to avoid crashing it.
To change this limit, set the config variable
`--ServerApp.iopub_msg_rate_limit`.
Current values:
ServerApp.iopub_msg_rate_limit={} (msgs/sec)
ServerApp.rate_limit_window={} (secs)
""".format(
self.iopub_msg_rate_limit, self.rate_limit_window
)
ServerApp.iopub_msg_rate_limit={self.iopub_msg_rate_limit} (msgs/sec)
ServerApp.rate_limit_window={self.rate_limit_window} (secs)
"""
),
msg["parent_header"],
)
Expand All @@ -734,19 +732,17 @@ def _limit_rate(self, channel, msg, msg_list):
)
self.write_stderr(
dedent(
"""\
f"""\
IOPub data rate exceeded.
The Jupyter server will temporarily stop sending output
to the client in order to avoid crashing it.
To change this limit, set the config variable
`--ServerApp.iopub_data_rate_limit`.
Current values:
ServerApp.iopub_data_rate_limit={} (bytes/sec)
ServerApp.rate_limit_window={} (secs)
""".format(
self.iopub_data_rate_limit, self.rate_limit_window
)
ServerApp.iopub_data_rate_limit={self.iopub_data_rate_limit} (bytes/sec)
ServerApp.rate_limit_window={self.rate_limit_window} (secs)
"""
),
msg["parent_header"],
)
Expand Down
1 change: 0 additions & 1 deletion jupyter_server/services/kernelspecs/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ def kernelspec_model(handler, name, spec_dict, resource_dir):
d = {"name": name, "spec": spec_dict, "resources": {}}

# Add resource files if they exist
resource_dir = resource_dir
for resource in ["kernel.js", "kernel.css"]:
if os.path.exists(pjoin(resource_dir, resource)):
d["resources"][resource] = url_path_join(
Expand Down
2 changes: 1 addition & 1 deletion jupyter_server/services/sessions/sessionmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def get(self, record: Union[KernelSessionRecord, str]) -> KernelSessionRecord:
"""
if isinstance(record, str):
for r in self._records:
if record == r.kernel_id or record == r.session_id:
if record in (r.kernel_id, r.session_id):
return r
elif isinstance(record, KernelSessionRecord):
for r in self._records:
Expand Down
4 changes: 2 additions & 2 deletions jupyter_server/traittypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ def validate(self, obj, value):
value = self._resolve_string(value)
except ImportError as e:
emsg = (
"The '{}' trait of {} instance must be a type, but "
"{!r} could not be imported".format(self.name, obj, value)
f"The '{self.name}' trait of {obj} instance must be a type, but "
f"{value!r} could not be imported"
)
raise TraitError(emsg) from e
try:
Expand Down
Loading

0 comments on commit 1cb4116

Please sign in to comment.