#!/usr/bin/env python """ safe_write.py - HTTP cache-friendly file writing safe_write allows you to use a process to generate a static file (usually, run by cron or at), while only changing the file on disk if the data has changed. This means that the file modification time changes only when the data changes; because this is what most Web servers use to generate the Last-Modified HTTP response header, this will result in better caching. safe_write can be used as a function in your program, or the library can be used as a command-line filter; % generate_some_data | safe_write.py targetfile.html """ __license__ = """ Copyright (c) 2004 Mark Nottingham Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ __version__ = '0.61' import sys, sha def safe_write(file, data): """ Write the data to the file only if it is different. This makes for better caching, since it won't change the Last-Modified date unless necessary. """ try: fh = open(file, 'r') cur_data = sha.new(fh.read()).digest() fh.close() except IOError: cur_data = None if cur_data != sha.new(data).digest(): fh = open(file, 'w') fh.write(data) fh.close() def usage(msg): sys.stderr.write("""\ %s USAGE: %s filename where filename is the target filename for writing. The data stream is read from STDIN. """ % (msg, sys.argv[0])) if __name__ == '__main__': try: safe_write(sys.argv[1], sys.stdin.read()) except Exception, msg: usage(msg)