sheenobu dot net

2021-02-21 - Python3 - no-cache HTTP file server

As titled. Standard python3 -m http.server does caching which is not ideal. If we want to provide args like python -m http.server --directory, you have to configure them inline when calling the test method.

#!/usr/bin/env python
import http.server
from functools import partial


class NoCacheHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_nocache_headers()
        super(NoCacheHTTPRequestHandler, self).end_headers()

    def send_nocache_headers(self):
        self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
        self.send_header("Pragma", "no-cache")
        self.send_header("Expires", "0")


if __name__ == '__main__':
    # had to pull this from http.server module
    handler_class = partial(NoCacheHTTPRequestHandler,
                            directory="build/")

    http.server.test(
        HandlerClass=handler_class,
        port=8000,
        bind=None,
    )
← Back to /snippets