Created
December 7, 2010 14:03
-
-
Save jonashaag/731810 to your computer and use it in GitHub Desktop.
WSGI middleware that automatically reloads the wrapped app if it changes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def app(env, start_response): | |
start_response('200 ok', []) | |
return 'hello\n' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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