如何在Jupyter Kernel Gateway自定义个性中添加HTTP Handler向内核发消息
/load_data HTTP Handler Since you already know how to add custom handlers to your Kernel Gateway setup, let’s dive straight into the core part: sending pre-defined messages to the kernel from your new /load_data endpoint. Below are two approaches tailored to your setup—using WebSocket (matching your existing WebSocket personality) and ZMQ (the default kernel communication layer).
Using WebSocket (Matching Your Existing Personality)
First, you’ll need to access the active WebSocket kernel client from your handler. Most Kernel Gateway personalities store this client in the application context. Here’s a practical Tornado-based example (the standard for Jupyter’s web stack):
from jupyter_client.session import Session from tornado.web import RequestHandler class LoadDataHandler(RequestHandler): def post(self): # Fetch the active kernel client from the app context (adjust based on your personality's implementation) kernel_client = self.application.kernel_client # Pre-defined code to open your specific file (customize path and logic as needed) load_data_code = """ with open('/absolute/path/to/your/target_file.txt', 'r') as file: # Add post-load logic here (e.g., parse CSV, store in a variable) loaded_content = file.read() print("File loaded successfully into 'loaded_content' variable") """ # Initialize a Jupyter session (reuse an existing one if available in your setup) session = Session(username="kernel_gateway_user") # Build a valid Jupyter kernel message (execute_request is the type for running code) execution_msg = session.msg( "execute_request", content={ "code": load_data_code, "silent": False, "store_history": True, "user_expressions": {}, "allow_stdin": False } ) # Send the message via WebSocket to the kernel kernel_client.send(execution_msg) # Send a success response back to the HTTP caller self.write({"status": "success", "detail": "Load data command sent to kernel"}) self.set_status(200)
Key Notes:
- Double-check where your personality stores the
kernel_client—some implementations might attach it to the request context instead of the application. - The message structure follows Jupyter’s kernel protocol strictly;
execute_requestis the correct message type for running code snippets. - Use absolute file paths to avoid confusion between the HTTP server’s working directory and the kernel’s.
Using ZMQ (Direct Kernel Communication)
If you prefer to bypass the WebSocket layer and communicate directly with the kernel via ZMQ (Kernel Gateway’s default kernel transport), use Jupyter’s official jupyter_client library. Here’s how to integrate this into your handler:
from jupyter_client import KernelClient from tornado.web import RequestHandler class LoadDataHandler(RequestHandler): # Pass the pre-configured ZMQ kernel client when registering the handler def initialize(self, kernel_client): self.kernel_client = kernel_client def post(self): # Pre-defined code to load your file load_data_code = """ import pandas as pd # Example: Use pandas for CSV files loaded_data = pd.read_csv('/absolute/path/to/your/data.csv') print(f"Loaded {len(loaded_data)} rows from the file") """ # Send the execution request directly via ZMQ self.kernel_client.execute(load_data_code) # Optional: Wait for the kernel's response (use async to avoid blocking the handler) # response_msg = self.kernel_client.get_shell_msg() # self.write({"status": "success", "kernel_response": response_msg["content"]}) self.write({"status": "success", "detail": "Load data command dispatched to kernel"}) self.set_status(200)
When registering this handler, pass the ZMQ kernel client:
# Assuming you have a pre-configured KernelClient instance application.add_handlers(r".*", [ (r"/load_data", LoadDataHandler, {"kernel_client": zmq_kernel_client}) ])
Key Notes:
- The
execute()method is a convenience wrapper fromjupyter_clientthat handles building the valid kernel message for you. - If you need to return the kernel’s output to the HTTP caller, use Tornado’s async/await pattern to listen for messages without blocking the handler thread.
内容的提问来源于stack exchange,提问作者Matthias123

