Context in Python
Here’s the translation of the Go code to Python, with explanations in Markdown format suitable for Hugo:
Our example demonstrates the usage of context.Context
for controlling cancellation in an HTTP server. A Context
carries deadlines, cancellation signals, and other request-scoped values across API boundaries and threads.
In this Python version:
We define a custom
CancellableHandler
that inherits fromhttp.server.SimpleHTTPRequestHandler
.The
hello
method simulates work that can be cancelled. It uses athreading.Event
to simulate context cancellation.We start a timer that will set the cancel event after 2 seconds, simulating a cancellation signal (like Ctrl+C in the original example).
The work simulation checks if the cancel event is set. If it is, it raises an exception.
If the work completes without cancellation, it sends a “hello” response. If cancelled, it sends an internal server error.
The
run_server
function sets up and starts the HTTP server.
To run the server:
In another terminal, you can test the server:
You should see output in the server terminal similar to:
This example demonstrates how you can implement cancellation in Python, which doesn’t have a direct equivalent to Go’s context.Context
. Instead, we use threading.Event
to simulate the cancellation mechanism.