Skip to content

Instantly share code, notes, and snippets.

@jonashaag
Created December 7, 2010 14:03
Show Gist options
  • Save jonashaag/731810 to your computer and use it in GitHub Desktop.
Save jonashaag/731810 to your computer and use it in GitHub Desktop.
WSGI middleware that automatically reloads the wrapped app if it changes
def app(env, start_response):
start_response('200 ok', [])
return 'hello\n'
import sys
import os
import inspect
class ReloadApplicationMiddleware(object):
def __init__(self, import_func):
self.import_func = import_func
self.app = import_func()
self.files = self.get_module_mtimes()
def get_module_mtimes(self):
files = {}
for module in sys.modules.itervalues():
try:
file = inspect.getsourcefile(module)
files[file] = os.stat(file).st_mtime
except TypeError:
continue
return files
def shall_reload(self):
for file, mtime in self.get_module_mtimes().iteritems():
if not file in self.files or self.files[file] < mtime:
self.files = self.get_module_mtimes()
return True
return False
def __call__(self, *args, **kwargs):
if self.shall_reload():
print 'Reloading...'
self.app = self.import_func()
return self.app(*args, **kwargs)
def import_app():
sys.modules.pop('realapp', None)
import realapp
return realapp.app
from bjoern import run
run(ReloadApplicationMiddleware(import_app), '0.0.0.0', 8080)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment