"Fossies" - the Fresh Open Source Software Archive

Member "cheetah3-3.2.6.post2/Cheetah/ImportHooks.py" (20 Apr 2021, 4430 Bytes) of package /linux/www/cheetah3-3.2.6.post2.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "ImportHooks.py" see the Fossies "Dox" file reference documentation and the last Fossies "Diffs" side-by-side code changes report: 3-3.2.2_vs_3-3.2.3.

    1 """
    2 Provides some import hooks to allow Cheetah's .tmpl files to be imported
    3 directly like Python .py modules.
    4 
    5 To use these:
    6   import Cheetah.ImportHooks
    7   Cheetah.ImportHooks.install()
    8 """
    9 
   10 try:
   11     from importlib import invalidate_caches
   12 except ImportError:
   13     invalidate_caches = None
   14 import sys
   15 import os.path
   16 import py_compile
   17 import types
   18 try:
   19     import builtins as builtin
   20 except ImportError:  # PY2
   21     import __builtin__ as builtin
   22 from threading import RLock
   23 import traceback
   24 
   25 from Cheetah import ImportManager
   26 from Cheetah.ImportManager import DirOwner
   27 from Cheetah.Compiler import Compiler
   28 from Cheetah.convertTmplPathToModuleName import convertTmplPathToModuleName
   29 
   30 _installed = False
   31 
   32 ##################################################
   33 # HELPER FUNCS
   34 
   35 _cacheDir = []
   36 
   37 
   38 def setCacheDir(cacheDir):
   39     global _cacheDir
   40     _cacheDir.append(cacheDir)
   41 
   42 ##################################################
   43 # CLASSES
   44 
   45 
   46 class CheetahDirOwner(DirOwner):
   47     _lock = RLock()
   48     _acquireLock = _lock.acquire
   49     _releaseLock = _lock.release
   50 
   51     templateFileExtensions = ('.tmpl',)
   52     debuglevel = 0
   53 
   54     def getmod(self, name):
   55         self._acquireLock()
   56         try:
   57             mod = DirOwner.getmod(self, name)
   58             if mod:
   59                 return mod
   60 
   61             for ext in self.templateFileExtensions:
   62                 tmplPath = os.path.join(self.path, name + ext)
   63                 if os.path.exists(tmplPath):
   64                     try:
   65                         return self._compile(name, tmplPath)
   66                     except Exception:
   67                         # @@TR: log the error
   68                         exc_txt = traceback.format_exc()
   69                         exc_txt = '  ' + ('  \n'.join(exc_txt.splitlines()))
   70                         raise ImportError(
   71                             'Error while compiling Cheetah module '
   72                             '%(name)s, original traceback follows:\n'
   73                             '%(exc_txt)s' % locals())
   74             return None
   75 
   76         finally:
   77             self._releaseLock()
   78 
   79     def _compile(self, name, tmplPath):
   80         if invalidate_caches:
   81             invalidate_caches()
   82 
   83         # @@ consider adding an ImportError raiser here
   84         code = str(Compiler(file=tmplPath, moduleName=name,
   85                             mainClassName=name))
   86         if _cacheDir:
   87             __file__ = os.path.join(
   88                 _cacheDir[0], convertTmplPathToModuleName(tmplPath)) + '.py'
   89         else:
   90             __file__ = os.path.splitext(tmplPath)[0] + '.py'
   91         try:
   92             with open(__file__, 'w') as _py_file:
   93                 _py_file.write(code)
   94         except (IOError, OSError):
   95             # @@ TR: need to add some error code here
   96             if self.debuglevel > 0:
   97                 traceback.print_exc(file=sys.stderr)
   98             __file__ = tmplPath
   99         else:
  100             try:
  101                 py_compile.compile(__file__)
  102             except IOError:
  103                 pass
  104         co = compile(code + '\n', __file__, 'exec')
  105 
  106         mod = types.ModuleType(name)
  107         mod.__file__ = co.co_filename
  108         if _cacheDir:
  109             # @@TR: this is used in the WebKit filemonitoring code
  110             mod.__orig_file__ = tmplPath
  111         mod.__co__ = co
  112         return mod
  113 
  114 
  115 ##################################################
  116 # FUNCTIONS
  117 
  118 def install(templateFileExtensions=('.tmpl',)):
  119     """Install the Cheetah Import Hooks"""
  120 
  121     global _installed
  122     if not _installed:
  123         CheetahDirOwner.templateFileExtensions = templateFileExtensions
  124         if isinstance(builtin.__import__, types.BuiltinFunctionType):
  125             global __oldimport__
  126             ImportManager.__oldimport__ = __oldimport__ = builtin.__import__
  127             ImportManager._globalOwnerTypes.insert(0, CheetahDirOwner)
  128             global _manager
  129             _manager = ImportManager.ImportManager()
  130             _manager.setThreaded()
  131             _manager.install()
  132             _installed = True
  133 
  134 
  135 def uninstall():
  136     """Uninstall the Cheetah Import Hooks"""
  137     global _installed
  138     if _installed:
  139         if isinstance(builtin.__import__, types.MethodType):
  140             builtin.__import__ = __oldimport__
  141             if ImportManager._globalOwnerTypes[0] is CheetahDirOwner:
  142                 del ImportManager._globalOwnerTypes[0]
  143             del ImportManager.__oldimport__
  144             global _manager
  145             del _manager
  146             _installed = False