1+ import base64
12import json
3+ import random
4+ from pathlib import Path
25
36from jupyter_server .base .handlers import APIHandler
47from jupyter_server .utils import url_path_join
58import tornado
69
10+ from .images_and_captions import IMAGES_AND_CAPTIONS
11+
12+ IMAGES_DIR = Path (__file__ ).parent .absolute () / "images"
13+
14+
715class 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+
2245def 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