Skip to content

Commit

Permalink
Apply auto-formatters
Browse files Browse the repository at this point in the history
  • Loading branch information
blink1073 committed Jan 17, 2024
1 parent 576c5e6 commit 32b06a6
Show file tree
Hide file tree
Showing 35 changed files with 134 additions and 150 deletions.
8 changes: 5 additions & 3 deletions conftest.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

import os
import logging
import pytest
import os
from binascii import hexlify

import pytest
from traitlets.config import Config

from kernel_gateway.gatewayapp import KernelGatewayApp

pytest_plugins = ["pytest_jupyter.jupyter_core", "pytest_jupyter.jupyter_server"]
Expand Down Expand Up @@ -98,7 +100,7 @@ def jp_server_cleanup(jp_asyncio_loop):
KernelGatewayApp.clear_instance()


@pytest.fixture
@pytest.fixture()
def jp_auth_header(jp_serverapp):
"""Configures an authorization header using the token from the serverapp fixture."""
return {"Authorization": f"token {jp_serverapp.identity_provider.token}"}
1 change: 0 additions & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its
# containing dir.
Expand Down
5 changes: 3 additions & 2 deletions etc/api_examples/setting_response_metadata.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,10 @@
},
"outputs": [],
"source": [
"import hashlib\n",
"import json\n",
"from dicttoxml import dicttoxml\n",
"import hashlib"
"\n",
"from dicttoxml import dicttoxml"
]
},
{
Expand Down
3 changes: 0 additions & 3 deletions kernel_gateway/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""Entrypoint for the kernel gateway package."""
from .gatewayapp import launch_instance

from ._version import version_info, __version__
1 change: 0 additions & 1 deletion kernel_gateway/__main__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""CLI entrypoint for the kernel gateway package."""
from __future__ import absolute_import

if __name__ == "__main__":
import kernel_gateway.gatewayapp as app
Expand Down
5 changes: 2 additions & 3 deletions kernel_gateway/auth/identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@
This defines the _authentication_ layer of Jupyter Server,
to be used in combination with Authorizer for _authorization_.
"""
from traitlets import default
from tornado import web

from jupyter_server.auth.identity import IdentityProvider, User
from jupyter_server.base.handlers import JupyterHandler
from tornado import web
from traitlets import default


class GatewayIdentityProvider(IdentityProvider):
Expand Down
7 changes: 3 additions & 4 deletions kernel_gateway/base/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
# Distributed under the terms of the Modified BSD License.
"""Tornado handlers for the base of the API."""

from tornado import web
import jupyter_server.base.handlers as server_handlers
from ..mixins import TokenAuthorizationMixin, CORSMixin, JSONErrorsMixin
from tornado import web

from ..mixins import CORSMixin, JSONErrorsMixin, TokenAuthorizationMixin


class APIVersionHandler(
Expand All @@ -14,8 +15,6 @@ class APIVersionHandler(
JSON errors.
"""

pass


class NotFoundHandler(JSONErrorsMixin, web.RequestHandler):
"""Catches all requests and responds with 404 JSON messages.
Expand Down
46 changes: 19 additions & 27 deletions kernel_gateway/gatewayapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,48 +4,40 @@

import asyncio
import errno
import importlib
import logging
import hashlib
import hmac
import importlib
import logging
import os
import sys
import signal
import select
import socket
import signal
import ssl
import sys
import threading
from base64 import encodebytes

import nbformat
from jupyter_server.services.kernels.kernelmanager import MappingKernelManager

from urllib.parse import urlparse
from traitlets import Unicode, Integer, Bytes, default, observe, Type, Instance, List, CBool

from jupyter_core.application import JupyterApp, base_aliases
import nbformat
from jupyter_client.kernelspec import KernelSpecManager

from tornado import httpserver
from tornado import web, ioloop
from tornado.log import enable_pretty_logging, LogFormatter

from jupyter_core.application import JupyterApp, base_aliases
from jupyter_core.paths import secure_write
from jupyter_server.auth.authorizer import AllowAllAuthorizer, Authorizer
from jupyter_server.serverapp import random_ports
from ._version import __version__
from .services.sessions.sessionmanager import SessionManager
from .services.kernels.manager import SeedingMappingKernelManager
from jupyter_server.services.kernels.connection.base import BaseKernelWebsocketConnection
from jupyter_server.services.kernels.connection.channels import ZMQChannelsWebsocketConnection
from jupyter_server.services.kernels.kernelmanager import MappingKernelManager
from tornado import httpserver, ioloop, web
from tornado.log import LogFormatter, enable_pretty_logging
from traitlets import Bytes, CBool, Instance, Integer, List, Type, Unicode, default, observe

from ._version import __version__
from .auth.identity import GatewayIdentityProvider
from .jupyter_websocket import JupyterWebsocketPersonality

# Only present for generating help documentation
from .notebook_http import NotebookHTTPPersonality
from .jupyter_websocket import JupyterWebsocketPersonality

from jupyter_server.auth.authorizer import AllowAllAuthorizer, Authorizer
from jupyter_server.services.kernels.connection.base import BaseKernelWebsocketConnection
from jupyter_server.services.kernels.connection.channels import ZMQChannelsWebsocketConnection

from .services.kernels.manager import SeedingMappingKernelManager
from .services.sessions.sessionmanager import SessionManager

# Add additional command line aliases
aliases = dict(base_aliases)
Expand Down Expand Up @@ -594,7 +586,7 @@ def init_configurables(self):
raise RuntimeError(msg)

api_module = self._load_api_module(self.api)
func = getattr(api_module, "create_personality")
func = api_module.create_personality
self.personality = func(parent=self, log=self.log)

self.io_loop.call_later(
Expand Down Expand Up @@ -701,7 +693,7 @@ def init_http_server(self):
for port in random_ports(self.port, self.port_retries + 1):
try:
self.http_server.listen(port, self.ip)
except socket.error as e:
except OSError as e:
if e.errno == errno.EADDRINUSE:
self.log.info("The port %i is already in use, trying another port." % port)
continue
Expand Down
10 changes: 6 additions & 4 deletions kernel_gateway/jupyter_websocket/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@
"""Jupyter websocket personality for the Kernel Gateway"""

import os

from jupyter_server.utils import url_path_join
from traitlets import Bool, List, default
from traitlets.config.configurable import LoggingConfigurable

from ..base.handlers import default_handlers as default_base_handlers
from ..services.kernels.pool import KernelPool
from ..services.kernels.handlers import default_handlers as default_kernel_handlers
from ..services.kernels.pool import KernelPool
from ..services.kernelspecs.handlers import default_handlers as default_kernelspec_handlers
from ..services.sessions.handlers import default_handlers as default_session_handlers
from .handlers import default_handlers as default_api_handlers
from jupyter_server.utils import url_path_join
from traitlets import Bool, List, default
from traitlets.config.configurable import LoggingConfigurable


class JupyterWebsocketPersonality(LoggingConfigurable):
Expand Down
9 changes: 5 additions & 4 deletions kernel_gateway/jupyter_websocket/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
# Distributed under the terms of the Modified BSD License.
"""Tornado handlers for kernel specs."""

import os

from tornado import web

from ..mixins import CORSMixin
import os


class BaseSpecHandler(CORSMixin, web.StaticFileHandler):
Expand All @@ -13,7 +15,6 @@ class BaseSpecHandler(CORSMixin, web.StaticFileHandler):
@staticmethod
def get_resource_metadata():
"""Returns the (resource, mime-type) for the handlers spec."""
pass

def initialize(self):
"""Initializes the instance of this class to serve files.
Expand Down Expand Up @@ -52,6 +53,6 @@ def get_resource_metadata():


default_handlers = [
("/api/{}".format(SpecJsonHandler.get_resource_metadata()[0]), SpecJsonHandler),
("/api/{}".format(APIYamlHandler.get_resource_metadata()[0]), APIYamlHandler),
(f"/api/{SpecJsonHandler.get_resource_metadata()[0]}", SpecJsonHandler),
(f"/api/{APIYamlHandler.get_resource_metadata()[0]}", APIYamlHandler),
]
11 changes: 6 additions & 5 deletions kernel_gateway/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
# Distributed under the terms of the Modified BSD License.
"""Mixins for Tornado handlers."""

from http.client import responses
import json
import traceback
from http.client import responses

from tornado import web


class CORSMixin(object):
class CORSMixin:
"""Mixes CORS headers into tornado.web.RequestHandlers."""

SETTINGS_TO_HEADERS = {
Expand Down Expand Up @@ -52,7 +53,7 @@ def options(self, *args, **kwargs):
self.finish()


class TokenAuthorizationMixin(object):
class TokenAuthorizationMixin:
"""Mixes token auth into tornado.web.RequestHandlers and
tornado.websocket.WebsocketHandlers.
"""
Expand All @@ -75,7 +76,7 @@ def prepare(self):
package.
"""
server_token = self.settings.get("kg_auth_token")
if server_token and not self.request.method == "OPTIONS":
if server_token and self.request.method != "OPTIONS":
client_token = self.get_argument("token", None)
if client_token is None:
client_token = self.request.headers.get("Authorization")
Expand All @@ -88,7 +89,7 @@ def prepare(self):
return super().prepare()


class JSONErrorsMixin(object):
class JSONErrorsMixin:
"""Mixes `write_error` into tornado.web.RequestHandlers to respond with
JSON format errors.
"""
Expand Down
21 changes: 11 additions & 10 deletions kernel_gateway/notebook_http/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@
# Distributed under the terms of the Modified BSD License.
"""Notebook HTTP personality for the Kernel Gateway"""

import importlib
import os

import tornado
import importlib
from jupyter_server.utils import url_path_join
from traitlets import Bool, Dict, Unicode, default
from traitlets.config.configurable import LoggingConfigurable

from ..base.handlers import default_handlers as default_base_handlers
from ..services.kernels.pool import ManagedKernelPool
from .cell.parser import APICellParser
from .handlers import NotebookAPIHandler, NotebookDownloadHandler, parameterize_path
from .swagger.handlers import SwaggerSpecHandler
from .handlers import NotebookAPIHandler, parameterize_path, NotebookDownloadHandler
from jupyter_server.utils import url_path_join
from traitlets import Bool, Unicode, Dict, default
from traitlets.config.configurable import LoggingConfigurable


class NotebookHTTPPersonality(LoggingConfigurable):
Expand Down Expand Up @@ -68,7 +69,7 @@ def __init__(self, *args, **kwargs):
# Import the module to use for cell endpoint parsing
cell_parser_module = importlib.import_module(self.cell_parser)
# Build the parser using the comment syntax for the notebook language
func = getattr(cell_parser_module, "create_parser")
func = cell_parser_module.create_parser
try:
kernel_language = self.parent.seed_notebook["metadata"]["language_info"]["name"]
except (AttributeError, KeyError):
Expand All @@ -95,13 +96,13 @@ def create_request_handlers(self):
# Register the NotebookDownloadHandler if configuration allows
if self.allow_notebook_download:
path = url_path_join("/", self.parent.base_url, r"/_api/source")
self.log.info("Registering resource: {}, methods: (GET)".format(path))
self.log.info(f"Registering resource: {path}, methods: (GET)")
handlers.append((path, NotebookDownloadHandler, {"path": self.parent.seed_uri}))

# Register a static path handler if configuration allows
if self.static_path is not None:
path = url_path_join("/", self.parent.base_url, r"/public/(.*)")
self.log.info("Registering resource: {}, methods: (GET)".format(path))
self.log.info(f"Registering resource: {path}, methods: (GET)")
handlers.append((path, tornado.web.StaticFileHandler, {"path": self.static_path}))

# Discover the notebook endpoints and their implementations
Expand Down Expand Up @@ -148,7 +149,7 @@ def create_request_handlers(self):
},
)
)
self.log.info("Registering resource: {}, methods: (GET)".format(path))
self.log.info(f"Registering resource: {path}, methods: (GET)")

# Add the 404 catch-all last
handlers.append(default_base_handlers[-1])
Expand Down
1 change: 1 addition & 0 deletions kernel_gateway/notebook_http/cell/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import re
import sys

from traitlets import Unicode
from traitlets.config.configurable import LoggingConfigurable

Expand Down
4 changes: 0 additions & 4 deletions kernel_gateway/notebook_http/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,8 @@ class CodeExecutionError(Exception):
request.
"""

pass


class UnsupportedMethodError(Exception):
"""Raised when a notebook-defined API does not support the requested HTTP
method.
"""

pass
Loading

0 comments on commit 32b06a6

Please sign in to comment.