To disable the browser cache on Python's simple HTTP server

Simple HTTP server http.server

A simple HTTP server for accessing local HTML files from a browser can be started with the following command if you have Python.

$ python -m http.server 8080
Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ...

If you execute this command and access http: // localhost: 8080 / with a browser on the same PC, index.html in the current directory will be displayed.

trouble

Even if the cache is effective in the browser and reloading, the browser may not make a request to the simple HTTP server, and even if you edit the local file, you may not be able to check it with the browser. You can clear the cache from your browser, but it's a hassle.

Therefore, the cache expiration date of 0 is included in the response from the simple HTTP server.

Cache-disabled Python script

import http.server
import sys

port = int(sys.argv[1])

class NoCacheHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Cache-Control', 'max-age=0')
        self.send_header('Expires', '0')
        super().end_headers()

httpServer = http.server.HTTPServer(('', port), NoCacheHTTPRequestHandler)
httpServer.serve_forever()

If you save this script with a name such as server.py, the following command will start the server.

$ python server.py 8080

You can also check the response header with the curl command. Open another terminal and run it.

$ curl -I http://localhost:8080/
HTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/3.8.3
Date: Thu, 12 Nov 2020 13:31:44 GMT
Content-type: text/html
Content-Length: 1178
Last-Modified: Thu, 12 Nov 2020 13:21:38 GMT
Cache-Control: max-age=0
Expires: 0

Your browser will now send you a request every time, and any changes to your local file will take effect immediately.

version information

$ python --version
Python 3.8.3

Recommended Posts

To disable the browser cache on Python's simple HTTP server
How to specify a public directory Python simple HTTP server
Quit Python's Simple HTTP Server triggered by an access log
Simple HTTP Server for python
A note on how to check the connection to the license server port
Script for backing up folders on the server to Google Drive
Notes on using matplotlib on the server
Save the audio data acquired by the browser in wav format on the server
Connect to VPN with your smartphone and turn off / on the server
Build a Pypi cache server on QNAP
Insufficient var space on the mail server
How to set the server time to Japanese time
How to manually update the AMP cache
Build a simple WebDAV server on Linux
Publish the current directory on the web server
[Flask + Keras] How to infer multiple models at high speed on the server
[Writing] I want to display the variables used in the program on the server side in real time on the browser and update them.