Skip to main content

An extendable replacement for http.server and its SimpleHTTPRequestHandler

Project description

simplehttpd
============

An extendable replacement for http.server and its SimpleHTTPRequestHandler

simplehttpd was written as a quick hack to extend SimpleHTTPRequestHandler in http.server to be more, well, extendable.
My specific need was to be able to quickly run an http server from the command line that also sent a custom header to the client
that forbade caching of the content served, in order to quickly iterate in my web development project, being sure that the content
truly was the latest content. The opportunity arose to make it more generally extendable, as you'll see from usage below.

Usage
=====
Once you install with
python setup.py install
or put simplehttpd wherever you need it, it mirrors the usage of http.server almost exactly.

The default port is 8000, but you can also set your own port.
python -m simplehttpd 8080
An alternative that allows more customization is:
python -c "import simplehttpd; simplehttpd.run(port=8080)"

But what if you want to send a custom header, like 'Cache-Control: no-cache' with every page load?
Well, simplehttpd.handler has an object called custom_headers which (by default) is an OrderedDict. So let's do this:
python -c "import simplehttpd; simplehttpd.handler.custom_headers['Cache-Control'] = 'no-cache'; simplehttpd.run()"

And for the really deep extending, you have even more options.
The custom header could be a callable that disallows caching files, but allows caching of directory lists.
def no_file_caching(response, file=None):
if file is not None:
self.send_header("Cache-Control", 'no-cache')
Which will be called at send time.

If you're really crazy, you could even replace methods on the handler class like send_custom_headers, which dispatches each custom header
Or replace the custom_headers OrderedDict on the handler class with your own kind of dict. It's just python, so let's hack!

Project details


Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page