flaskext_compat.py
This file
Path
scripts/flaskext_compat.py
125 lines · 4.9 KiB · Python
Last changed by
Merge branch '0.10-maintenance'Daniel Neuhäuserbefore adoptiond517f35
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 flaskext_compat4 ~~~~~~~~~~~~~~~56 Implements the ``flask.ext`` virtual package for versions of Flask7 older than 0.7. This module is a noop if Flask 0.8 was detected.89 Usage::1011 import flaskext_compat12 flaskext_compat.activate()13 from flask.ext import foo1415 :copyright: (c) 2014 by Armin Ronacher.16 :license: BSD, see LICENSE for more details.17"""18import sys19import os20import imp212223class ExtensionImporter(object):24 """This importer redirects imports from this submodule to other locations.25 This makes it possible to transition from the old flaskext.name to the26 newer flask_name without people having a hard time.27 """2829 def __init__(self, module_choices, wrapper_module):30 self.module_choices = module_choices31 self.wrapper_module = wrapper_module32 self.prefix = wrapper_module + '.'33 self.prefix_cutoff = wrapper_module.count('.') + 13435 def __eq__(self, other):36 return self.__class__.__module__ == other.__class__.__module__ and \37 self.__class__.__name__ == other.__class__.__name__ and \38 self.wrapper_module == other.wrapper_module and \39 self.module_choices == other.module_choices4041 def __ne__(self, other):42 return not self.__eq__(other)4344 def install(self):45 sys.meta_path[:] = [x for x in sys.meta_path if self != x] + [self]4647 def find_module(self, fullname):48 if fullname.startswith(self.prefix):49 return self5051 def load_module(self, fullname):52 if fullname in sys.modules:53 return sys.modules[fullname]54 modname = fullname.split('.', self.prefix_cutoff)[self.prefix_cutoff]55 for path in self.module_choices:56 realname = path % modname57 try:58 __import__(realname)59 except ImportError:60 exc_type, exc_value, tb = sys.exc_info()61 # since we only establish the entry in sys.modules at the62 # end this seems to be redundant, but if recursive imports63 # happen we will call into the move import a second time.64 # On the second invocation we still don't have an entry for65 # fullname in sys.modules, but we will end up with the same66 # fake module name and that import will succeed since this67 # one already has a temporary entry in the modules dict.68 # Since this one "succeeded" temporarily that second69 # invocation now will have created a fullname entry in70 # sys.modules which we have to kill.71 sys.modules.pop(fullname, None)7273 # If it's an important traceback we reraise it, otherwise74 # we swallow it and try the next choice. The skipped frame75 # is the one from __import__ above which we don't care about.76 if self.is_important_traceback(realname, tb):77 raise exc_type, exc_value, tb.tb_next78 continue79 module = sys.modules[fullname] = sys.modules[realname]80 if '.' not in modname:81 setattr(sys.modules[self.wrapper_module], modname, module)82 return module83 raise ImportError('No module named %s' % fullname)8485 def is_important_traceback(self, important_module, tb):86 """Walks a traceback's frames and checks if any of the frames87 originated in the given important module. If that is the case then we88 were able to import the module itself but apparently something went89 wrong when the module was imported. (Eg: import of an import failed).90 """91 while tb is not None:92 if self.is_important_frame(important_module, tb):93 return True94 tb = tb.tb_next95 return False9697 def is_important_frame(self, important_module, tb):98 """Checks a single frame if it's important."""99 g = tb.tb_frame.f_globals100 if '__name__' not in g:101 return False102103 module_name = g['__name__']104105 # Python 2.7 Behavior. Modules are cleaned up late so the106 # name shows up properly here. Success!107 if module_name == important_module:108 return True109110 # Some python versions will clean up modules so early that the111 # module name at that point is no longer set. Try guessing from112 # the filename then.113 filename = os.path.abspath(tb.tb_frame.f_code.co_filename)114 test_string = os.path.sep + important_module.replace('.', os.path.sep)115 return test_string + '.py' in filename or \116 test_string + os.path.sep + '__init__.py' in filename117118119def activate():120 import flask121 ext_module = imp.new_module('flask.ext')122 ext_module.__path__ = []123 flask.ext = sys.modules['flask.ext'] = ext_module124 importer = ExtensionImporter(['flask_%s', 'flaskext.%s'], 'flask.ext')125 importer.install()