Skip to content
Myr

flaskext_compat.py

This file

Path

scripts/flaskext_compat.py

124 lines · 4.9 KiB · Python

Last changed by

Refactored flask.ext process to not swallow exceptions on weird Pythons.Armin Ronacherbefore adoption95c4dcb

History of this file

Take 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        from flask.ext import foo1314    :copyright: (c) 2011 by Armin Ronacher.15    :license: BSD, see LICENSE for more details.16"""17import sys18import os19import imp202122class ExtensionImporter(object):23    """This importer redirects imports from this submodule to other locations.24    This makes it possible to transition from the old flaskext.name to the25    newer flask_name without people having a hard time.26    """2728    def __init__(self, module_choices, wrapper_module):29        self.module_choices = module_choices30        self.wrapper_module = wrapper_module31        self.prefix = wrapper_module + '.'32        self.prefix_cutoff = wrapper_module.count('.') + 13334    def __eq__(self, other):35        return self.__class__.__module__ == other.__class__.__module__ and \36               self.__class__.__name__ == other.__class__.__name__ and \37               self.wrapper_module == other.wrapper_module and \38               self.module_choices == other.module_choices3940    def __ne__(self, other):41        return not self.__eq__(other)4243    def install(self):44        sys.meta_path[:] = [x for x in sys.meta_path if self != x] + [self]4546    def find_module(self, fullname, path=None):47        if fullname.startswith(self.prefix):48            return self4950    def load_module(self, fullname):51        if fullname in sys.modules:52            return sys.modules[fullname]53        modname = fullname.split('.', self.prefix_cutoff)[self.prefix_cutoff]54        for path in self.module_choices:55            realname = path % modname56            try:57                __import__(realname)58            except ImportError:59                exc_type, exc_value, tb = sys.exc_info()60                # since we only establish the entry in sys.modules at the61                # very this seems to be redundant, but if recursive imports62                # happen we will call into the move import a second time.63                # On the second invocation we still don't have an entry for64                # fullname in sys.modules, but we will end up with the same65                # fake module name and that import will succeed since this66                # one already has a temporary entry in the modules dict.67                # Since this one "succeeded" temporarily that second68                # invocation now will have created a fullname entry in69                # sys.modules which we have to kill.70                sys.modules.pop(fullname, None)7172                # If it's an important traceback we reraise it, otherwise73                # we swallow it and try the next choice.  The skipped frame74                # is the one from __import__ above which we don't care about75                if self.is_important_traceback(realname, tb):76                    raise exc_type, exc_value, tb.tb_next77                continue78            module = sys.modules[fullname] = sys.modules[realname]79            if '.' not in modname:80                setattr(sys.modules[self.wrapper_module], modname, module)81            return module82        raise ImportError('No module named %s' % fullname)8384    def is_important_traceback(self, important_module, tb):85        """Walks a traceback's frames and checks if any of the frames86        originated in the given important module.  If that is the case then we87        were able to import the module itself but apparently something went88        wrong when the module was imported.  (Eg: import of an import failed).89        """90        while tb is not None:91            if self.is_important_frame(important_module, tb):92                return True93            tb = tb.tb_next94        return False9596    def is_important_frame(self, important_module, tb):97        """Checks a single frame if it's important."""98        g = tb.tb_frame.f_globals99        if '__name__' not in g:100            return False101102        module_name = g['__name__']103104        # Python 2.7 Behavior.  Modules are cleaned up late so the105        # name shows up properly here.  Success!106        if module_name == important_module:107            return True108109        # Some python verisons will will clean up modules so early that the110        # module name at that point is no longer set.  Try guessing from111        # the filename then.112        filename = os.path.abspath(tb.tb_frame.f_code.co_filename)113        test_string = os.path.sep + important_module.replace('.', os.path.sep)114        return test_string + '.py' in filename or \115               test_string + os.path.sep + '__init__.py' in filename116117118def activate():119    import flask120    ext_module = imp.new_module('flask.ext')121    ext_module.__path__ = []122    flask.ext = sys.modules['flask.ext'] = ext_module123    importer = ExtensionImporter(['flask_%s', 'flaskext.%s'], 'flask.ext')124    importer.install()