jump to navigation

FastCGI + python + update trick 2006 March 15 14:43

Posted by diamond in : Work , add a comment

I’m currently writing some fastcgi stuff using python. One of the things you have to remember when using fastcgi is that the process is persistent. If you update the code, it won’t take effect until the process is restarted. So, after some thought, i came up with a solution:

import os
import stat
import jon.cgi as cgi
import jon.fcgi as fcgi

class Handler(cgi.Handler):
    def process(self, req):
        s = os.stat(req.environ['SCRIPT_FILENAME'])
        if s[stat.ST_MTIME] > start_time:
            req.error('Newer version available')
            req.set_header("Location", req.environ['REQUEST_URI'])
            req.output_headers()
            server.exit()
        #do stuff
        ....

start_time = time.time()
server = fcgi.Server({fcgi.FCGI_RESPONDER: Handler})
server.run()

At the start of a request, it checks to see if it has been updated. If so, it outputs a http Location: header with the current url to tell the browser reload, then exits. When the browser re-requests the page, apache will then restart the fcgi process, and voilá, updated script running, no glitches visible to the user. Only 6 of the above lines are related to this, all the rest are just for context and would normally exist anyway.

Fwiw, i’m using the jonpy cgi modules as python doesn’t have fastcgi support as standard.