Skip to content

Commit 7a18b68

Browse files
committed
Add server route to serve images and captions
1 parent 14eaaa2 commit 7a18b68

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Public domain images from https://www.loc.gov/free-to-use/cats/
2+
IMAGES_AND_CAPTIONS = [
3+
{ "filename": "brunnhilde.jpg", "caption": "Brünnhilde" },
4+
{ "filename": "cats.jpg", "caption": "Cats" },
5+
{ "filename": "cat-cher-evolution.jpg", "caption": "Evolution of a cat-cher" },
6+
{ "filename": "the-entanglement.jpg", "caption": "The entanglement" },
7+
]

jupytercon2025_extension_workshop/routes.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,17 @@
1+
import base64
12
import json
3+
import random
4+
from pathlib import Path
25

36
from jupyter_server.base.handlers import APIHandler
47
from jupyter_server.utils import url_path_join
58
import tornado
69

10+
from .images_and_captions import IMAGES_AND_CAPTIONS
11+
12+
IMAGES_DIR = Path(__file__).parent.absolute() / "images"
13+
14+
715
class HelloRouteHandler(APIHandler):
816
# The following decorator should be present on all verb methods (head, get, post,
917
# patch, put, delete, options) to ensure only authorized user can request the
@@ -19,11 +27,30 @@ def get(self):
1927
}))
2028

2129

30+
class ImageAndCaptionRouteHandler(APIHandler):
31+
@tornado.web.authenticated
32+
def get(self):
33+
random_selection = random.choice(IMAGES_AND_CAPTIONS)
34+
35+
# Read the data and encode the bytes in base64
36+
with open(IMAGES_DIR / random_selection["filename"], "rb") as f:
37+
b64_bytes = base64.b64encode(f.read()).decode("utf-8")
38+
39+
self.finish(json.dumps({
40+
"b64_bytes": b64_bytes,
41+
"caption": random_selection["caption"],
42+
}))
43+
44+
2245
def setup_route_handlers(web_app):
2346
host_pattern = ".*$"
2447
base_url = web_app.settings["base_url"]
2548

2649
hello_route_pattern = url_path_join(base_url, "jupytercon2025-extension-workshop", "hello")
27-
handlers = [(hello_route_pattern, HelloRouteHandler)]
50+
image_route_pattern = url_path_join(base_url, "jupytercon2025-extension-workshop", "random-image-caption")
51+
handlers = [
52+
(hello_route_pattern, HelloRouteHandler),
53+
(image_route_pattern, ImageAndCaptionRouteHandler),
54+
]
2855

2956
web_app.add_handlers(host_pattern, handlers)

0 commit comments

Comments
 (0)