Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke Python SimpleHTTPServer from command line with no cache option

Tags:

python

On Windows 7, I am using the command line

python -m SimpleHTTPServer 8888 

to invoke a simple web server to serve files from a directory, for development.

The problem is that the server seems to keep the files in cache. Old versions of files are served despite newer ones being available.

Is there a way to specify the "no cache" option from the command line directly?

like image 863
Ming K Avatar asked Aug 30 '12 09:08

Ming K


People also ask

How do I close an HTTP server in python?

CTRL+C is pressed to stop the server.


2 Answers

Perhaps this may work. Save the following to a file:

serveit.py

#!/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) 

then run it using

python serveit.py 8000 

to serve the current directory on port 8000. This was totally pulled from this gist, and seems to work great!

NOTE: If you're just looking to run a local webserver to serve static content, you may be interested in a precanned node solution to do this => http-server, which I've been using and seems to work great.

Also if you're on a mac, if you run this as root you can run it on port 80 or 443! For example

sudo python serveit.py 80

should allow you to run it and access it in your browser at http://localhost

like image 55
Brad Parks Avatar answered Sep 22 '22 20:09

Brad Parks


Of course the script above will not work for Python 3.x, but it just consists of changing the SimpleHTTPServer to http.server as shown below:

#!/usr/bin/env python3  import http.server  class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):     def end_headers(self):         self.send_my_headers()         http.server.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__':     http.server.test(HandlerClass=MyHTTPRequestHandler) 
like image 26
DBrown Avatar answered Sep 23 '22 20:09

DBrown