Debian Codegraph @

Cheetah/LoadTemplate.py

raw symbols SCIP
1 import os
2 import sys
3 from .ImportHooks import CheetahDirOwner
4 from .compat import ModuleNotFoundError
5
6
7 def loadTemplateModule(templatePath, debuglevel=0):
8 """Load template's module by full or relative path (extension is optional)
9
10 Examples:
11
12 template = loadTemplateModule('views/index')
13 template = loadTemplateClass('views/index.tmpl')
14
15 Template is loaded from from .py[co], .py or .tmpl -
16 whatever will be found. Files *.tmpl are compiled to *.py;
17 *.py are byte-compiled to *.py[co]. Compiled files are cached
18 in the template directory. Errors on writing are silently ignored.
19 """
20 drive, localPath = os.path.splitdrive(templatePath)
21 dirname, filename = os.path.split(localPath)
22 filename, ext = os.path.splitext(filename)
23 if dirname:
24 # Cleanup: Convert /Templates//views/ -> /Templates/views
25 dirname_list = dirname.replace(os.sep, '/').split('/')
26 dirname_list = [d for (i, d) in enumerate(dirname_list)
27 if i == 0 or d] # Preserve root slash
28 dirname = os.sep.join(dirname_list)
29 template_dir = CheetahDirOwner(drive + dirname)
30 if ext:
31 template_dir.templateFileExtensions = (ext,)
32 template_dir.debuglevel = debuglevel
33 mod = template_dir.getmod(filename)
34 if mod is None:
35 raise ModuleNotFoundError("Cannot find {}".format(templatePath))
36 mod.__name__ = filename
37 sys.modules[filename] = mod
38 co = mod.__co__
39 del mod.__co__
40 exec(co, mod.__dict__)
41 return mod
42
43
44 def loadTemplateClass(templatePath, debuglevel=0):
45 """Load template's class by full or relative path"""
46 mod = loadTemplateModule(templatePath, debuglevel=debuglevel)
47 return getattr(mod, mod.__name__)