Serving content during development
Python's SimpleHTTPServer
is my goto friend for serving HTTP requests locally while developing stuff. Sometimes however you get caught with the browser caching things that you really don't want it to. CTRL+F5 usually works (it's a hardcoded pattern for me by now) but today I stumbled on a gotcha: cached JSON content that a page was pulling in.
The solution for me, was to modify SimpleHTTPServer to set HTTP headers to tell the browser not to cache. Here's the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #!/usr/bin/env python
import SimpleHTTPServer
class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
def send_my_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__':
SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
|
Usage: python serveit.py 8080
to serve the local directory on port 8080.
Source: The ever helpful stackoverflow