Tuesday, February 27, 2007

Autoupdate application modules

It's pretty easy to reload modules in Python. Using this feature you can update you whole application to a new version, without leaving or restarting your application.

The code below updates all loaded modules with newer version from any given path. To be included in the update, the module must contain the attribute autoupdate and a version attribute.

import sys
import os

def check(path):
""" Update all modules containing a autoupdate attribute
"""
for name,mod in sys.modules.items():
if hasattr(mod,'autoupdate'):
last_version=getattr(mod,'version')
print "Testing update of : %s v. %d" % (name,last_version)
org_file=os.path.split(mod.__file__)[1].replace('.pyc','.py')
new_module_file="%s\\%s.%d" % (path,org_file,last_version+1)
if os.path.exists(new_module_file):
print "Update found: %s" % new_module_file
update=file(new_module_file,'rb').read()
destination="%s\\%s" % (os.getcwd(), org_file)
print "Will replace: %s" % destination
#os.remove(destination)
#file(destination,'wb').write(update)
reload(mod)


This only works for modules that can work after a reload. Fx. SQLObject has a problem with that...

It would be an easy task to extend this to autoupdate from a FTP- or website.

No comments: