Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add GET/PUT file ID/path handlers #12

Merged
merged 4 commits into from
Oct 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions jupyter_server_fileid/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

from jupyter_server_fileid.manager import FileIdManager

from .handlers import FileId2PathHandler, FilePath2IdHandler


class FileIdExtension(ExtensionApp):

Expand Down Expand Up @@ -44,3 +46,17 @@ async def cm_listener(logger: EventLogger, schema_id: str, data: dict) -> None:
schema_id="https://events.jupyter.org/jupyter_server/contents_service/v1",
listener=cm_listener,
)

def initialize_handlers(self):
self.handlers.extend(
[
(
r"/api/fileid/id/(.*)",
FilePath2IdHandler,
),
(
r"/api/fileid/path/(.*)",
FileId2PathHandler,
),
],
)
64 changes: 64 additions & 0 deletions jupyter_server_fileid/handlers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from jupyter_server.auth import authorized
from jupyter_server.base.handlers import APIHandler
from tornado import web

AUTH_RESOURCE = "contents"


class FileIdAPIHandler(APIHandler):
auth_resource = AUTH_RESOURCE


class FilePath2IdHandler(FileIdAPIHandler):
@web.authenticated
@authorized
async def get(self, path):
manager = self.settings["file_id_manager"]

idx = manager.get_id(path)
if idx is None:
# index does not exist
raise web.HTTPError(404, f"No ID found for file {path!r}")

# index exists, return it
return self.finish(str(idx))

@web.authenticated
@authorized
async def put(self, path):
manager = self.settings["file_id_manager"]

idx = manager.get_id(path)
if idx is not None:
# index already exists
self.set_status(200)
return self.finish(str(idx))

# try indexing
idx = manager.index(path)
if idx is None:
# file does not exists
raise web.HTTPError(404, f"File {path!r} does not exist")

# index successfully created
self.set_status(201)
return self.finish(str(idx))


class FileId2PathHandler(FileIdAPIHandler):
@web.authenticated
@authorized
async def get(self, idx):
manager = self.settings["file_id_manager"]

path = manager.get_path(idx)

if path is None:
raise web.HTTPError(404, f"No path found for ID {idx!r}")

return self.finish(str(path))

@web.authenticated
@authorized
async def put(self, idx):
raise web.HTTPError(501, "Cannot set a file's ID")