def get_dirs(self): # Explicitly defined directories try: dirs = tuple([ os.path.join(d, "mote", "projects") \ for d in settings.MOTE["directories"] ]) except (AttributeError, KeyError): dirs = () # App directories. Note the testing environment does not require upward # traversal. result = dirs + get_app_template_dirs(os.path.join("..", "mote", "projects")) \ + get_app_template_dirs(os.path.join("mote", "projects")) return result
def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons. """ if not template_dirs: template_dirs = settings.TEMPLATE_DIRS template_dirs = get_app_template_dirs('templates') + template_dirs language = get_language() if language: lang_path = join('multilang', language) else: lang_path = None for template_dir in template_dirs: # We need specific language templates tried first, then base folder, then Russian as fallback for path in (lang_path, "", "multilang/ru"): if path is not None: try: yield safe_join(template_dir, path, template_name) except UnicodeDecodeError: # The template dir name was a bytestring that wasn't valid UTF-8. raise except ValueError: # The joined path was located outside of this particular # template_dir (it might be inside another one, so this isn't # fatal). pass
def list_templates(request): template_dirs = [s for s in get_app_template_dirs('templates') if re.match(r'.*/foodsaving/.*', s)] template_names = set() templates = {} for directory in template_dirs: for directory, dirnames, filenames in os.walk(directory): relative_dir = directory[len(foodsaving_basedir) + 1:] for filename in filenames: if re.match(r'.*\.jinja2$', filename) and not re.match(r'.*\.slack\.jinja2$', filename): path = os.path.join(relative_dir, filename) # strip out anything past the first dot for the name name = re.sub(r'\..*$', '', os.path.basename(path)) if name != 'template_preview_list': template_names.add(name) formats = [] for idx, s in enumerate(['subject', 'text', 'html']): if os.path.isfile('{}.{}.jinja2'.format(os.path.join(directory, name), s)): formats.append(s) templates[name] = { 'name': name, 'has_handler': name in dir(handlers), 'formats': formats, } return HttpResponse(render_to_string('template_preview_list.jinja2', { 'templates': sorted(templates.values(), key=lambda t: t['name']) }))
def watched_paths(self): """ list of paths to be watched for modifications on static files. Returns: all static and template locations for all apps included in DJANGO_LIVESYNC.INCLUDED_APPS. """ tmpls = [ os.path.join(d, 'templates') for d in get_app_template_dirs('') if d.startswith(settings.BASE_DIR) and os.path.basename( d) in settings.DJANGO_LIVESYNC['INCLUDED_APPS'] and os.path.exists(os.path.join(d, 'templates')) ] paths = set( itertools.chain( getattr(settings, 'STATICFILES_DIRS', []), getattr(settings, 'TEMPLATE_DIRS', []), # django backward compatibility. tmpls, )) paths.update(*[tmpl['DIRS'] for tmpl in settings.TEMPLATES]) if apps.is_installed('django.contrib.staticfiles'): from django.contrib.staticfiles.finders import get_finder finder = get_finder( 'django.contrib.staticfiles.finders.AppDirectoriesFinder') paths.update([ st.location for app, st in finder.storages.items() if app in settings.DJANGO_LIVESYNC['INCLUDED_APPS'] ]) return paths
def get_available_templates(template_dir): """ Helper method for returning a list of available email templates. Template needs to be a `*.txt` file and can have a HTML counterpart. :return: list of available email templates paths :rtype: list of tuples """ templates_dir = get_app_template_dirs(template_dir) txt_templates = list() for template_dir in templates_dir: txt_templates += glob.glob(os.path.join(template_dir, '*.txt')) templates = list() for template in txt_templates: file_name, _ = os.path.splitext(os.path.basename(template)) is_html_available = os.path.isfile(template.replace('.txt', '.html')) if is_html_available: label = '{} (txt + html)'.format(file_name) else: label = '{} (txt)'.format(file_name) templates.append((template.split('templates/')[1], label)) return templates
def test_compress_offline(self): template_dir_list = [] for template_dir in get_app_template_dirs('templates'): if str(template_dir).startswith(settings.BASE_DIR): template_dir_list.append(template_dir) template_list = [] for template_dir in template_dir_list: for base_dir, dirnames, filenames in os.walk(template_dir): for filename in filenames: template_list.append(os.path.join(base_dir, filename)) # Filter lines that are not html and strip whitespace filenames = [ name for name in [name.strip() for name in template_list] if name.endswith('.html') ] for filename in filenames: with open(filename, 'r') as f: in_compress_block = False for line in f.readlines(): has_start_tag = COMPRESS_JS in line or COMPRESS_CSS in line has_end_tag = ENDCOMPRESS in line if has_start_tag and not has_end_tag: in_compress_block = True continue if has_end_tag: in_compress_block = False if in_compress_block: self._assert_valid_import(line, filename)
def get_template_choices(templates_dir_name='emailtemplates', suffix='.html'): """ returns list of html templates from emailtemplates/*/ """ templates_list = [] try: # for Django < 1.8 template_dirs = settings.TEMPLATE_DIRS except AttributeError: # for Django >= 1.8 template_dirs = [] for template_setting in settings.TEMPLATES: template_dirs += template_setting['DIRS'] template_dirs = tuple(template_dirs) for template_dir_path in (template_dirs + get_app_template_dirs('templates')): path = os.path.join(template_dir_path, templates_dir_name) for root, dirs, files in os.walk(path): for name in files: filename = os.path.join(root, name).replace(path, '') if filename.endswith(suffix): templates_list.append(filename[1:]) return [(template_name, template_name) for template_name in list(set(templates_list))]
def handle(self, **options): ext = '.html' dump_dir = options.get('dir') apps = options.get('apps') # Decide from where to load templates if dump_dir: base_path = os.path.join(dump_dir, conf.TEMPLATES_DIR_NAME, conf.TEMPLATE_PREFIX) print(f'Load templates from: {base_path}\n') template_dirs = [base_path] elif apps: print(f'Load templates from Django Apps\n') app_dirs = get_app_template_dirs('templates') template_dirs = [d for d in app_dirs if os.path.isdir(d)] else: print('Must choose an option: --dir or --apps') return print('Loading:') num_created = 0 for _dir in template_dirs: answer = input(f'Load {_dir}? [y/N] ') if answer and 'y' == answer.lower(): num = load_dir(_dir, ext) num_created += num print(f'\nLoaded: {num_created}')
def template_dirs(self): """ Return a list of directories to search for templates. """ # Immutable return value because it's cached and shared by callers. template_dirs = tuple(self.dirs) if self.app_dirs: template_dirs += get_app_template_dirs(self.app_dirname) return template_dirs
def template_dirs(self): """ Returns a list of directories to search for templates. """ # Immutable return value because it's cached and shared by callers. template_dirs = tuple(self.dirs) if self.app_dirs: template_dirs += get_app_template_dirs(self.app_dirname) return template_dirs
def __init__(self, forms_dir='forms', engine=None): if engine is None: engine = Engine.get_default() self._engine = engine self._forms_dirs = get_app_template_dirs(forms_dir) self._forms_loader = Loader(self) self.use_form_tags = False self.context_processors = self._engine.context_processors + ['template_forms.posted_answers']
def get_app_template_dirs(): if django.VERSION < (1, 8): # noinspection PyUnresolvedReferences from django.template.loaders.app_directories import app_template_dirs else: # Django 1.8's template loader is refactored # noinspection PyUnresolvedReferences from django.template.utils import get_app_template_dirs app_template_dirs = get_app_template_dirs('templates') return list(app_template_dirs)
def _fix_coffin_post(self): try: from django.template.loaders.app_directories import ( app_template_dirs) except ImportError: from django.template.utils import get_app_template_dirs import django.template.loaders.app_directories django.template.loaders.app_directories.app_template_dirs = ( get_app_template_dirs('templates')) else: app_template_dirs = app_template_dirs
def test_template_mtime(self): template_name = "pages/team.html" template_dirs = get_app_template_dirs('templates') template_mtime = None for template_dir in template_dirs: try: template_path = safe_join(template_dir, template_name) a = datetime.fromtimestamp(os.stat(template_path).st_mtime) template_mtime = tz.make_aware(a) except: continue
def template_mtime(template_name): template_dirs = get_app_template_dirs('templates') template_mtime=None for template_dir in template_dirs: try: template_path = safe_join(template_dir, template_name) template_mtime = datetime.fromtimestamp(os.stat(template_path).st_mtime) template_mtime = tz.make_aware(template_mtime) except: continue return template_mtime
def _fix_coffin_post(self): try: from django.template.loaders.app_directories import ( app_template_dirs) except ImportError: from django.template.utils import get_app_template_dirs import django.template.loaders.app_directories django.template.loaders.app_directories.app_template_dirs = ( get_app_template_dirs('templates') ) else: app_template_dirs = app_template_dirs
def __init__(self, forms_dir='forms', engine=None): if engine is None: engine = Engine.get_default() self._engine = engine self._forms_dirs = get_app_template_dirs(forms_dir) self._forms_loader = Loader(self) self.use_form_tags = False self.context_processors = self._engine.context_processors + [ 'template_forms.posted_answers' ]
def get_available_page_templates(): """ Получаем названия доступных шаблонов для Pages во всех приложениях проекта. """ template_files = [] for template_dir in get_app_template_dirs('templates'): pages_template_dir = '%s/%s' % (template_dir, settings.ARTICLES_TEMPLATE_DIR) if os.path.isdir(pages_template_dir): for file in os.listdir(pages_template_dir): if file.endswith('.html'): template_files.append(file[:-5]) return list(set(template_files))
def get_cms_pages(base_dir="cms_lite", sub_dirs=[]): templates = [] for app_template_dir in get_app_template_dirs("templates"): cms_lite_dir = os.path.join(app_template_dir, "cms_lite", *sub_dirs) for root, subFolders, files in os.walk(cms_lite_dir): templates.extend([ reverse("cms_lite_page", args=[ re.sub(r"_", "-", re.sub(r"\/?index", "", re.sub(r"\.html$", "", os.path.relpath(os.path.join(root, f), cms_lite_dir)))) ]) for f in files if not f.startswith("_") and f.endswith(".html") ]) return sorted(set(templates))
def get_dirs(self): base_dir = getattr( settings, "MARKDOWN_VIEW_BASE_DIR", getattr( settings, "BASE_DIR", None) ) dirs = [*get_app_template_dirs('')] if base_dir: dirs.extend([base_dir]) return dirs
def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons. """ if not template_dirs: template_dirs = get_app_template_dirs("templates") for template_dir in template_dirs: try: yield safe_join(template_dir, template_name) except SuspiciousFileOperation: # The joined path was located outside of this template_dir # (it might be inside another one, so this isn't fatal). pass
def get_template_choices(templates_dir_name='emailtemplates', suffix='.html'): """ returns list of html templates from emailtemplates/*/ """ templates_list = [] for template_dir_path in (settings.TEMPLATE_DIRS + get_app_template_dirs('templates')): path = os.path.join(template_dir_path, templates_dir_name) for root, dirs, files in os.walk(path): for name in files: filename = os.path.join(root, name).replace(path, '') if filename.endswith(suffix): templates_list.append(filename[1:]) return [(template_name, template_name) for template_name in list(set(templates_list))]
def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons. """ if not template_dirs: template_dirs = get_app_template_dirs('templates') for template_dir in template_dirs: try: yield safe_join(template_dir, template_name) except SuspiciousFileOperation: # The joined path was located outside of this template_dir # (it might be inside another one, so this isn't fatal). pass
def list_templates(request): template_dirs = [ str(path) for path in get_app_template_dirs('templates') if re.match(r'.*/karrot/.*', str(path)) ] template_names = set() templates = {} for directory in template_dirs: for directory, dirnames, filenames in os.walk(directory): relative_dir = directory[len(basedir) + 1:] for filename in filenames: if re.match(r'.*\.jinja2$', filename) and not re.match( r'.*\.nopreview\.jinja2$', filename): path = os.path.join(relative_dir, filename) # strip out anything past the first dot for the name name = re.sub(r'\..*$', '', os.path.basename(path)) if name != 'template_preview_list': template_names.add(name) formats = [] for idx, s in enumerate(['subject', 'text', 'html']): if os.path.isfile('{}.{}.jinja2'.format( os.path.join(directory, name), s)): formats.append(s) elif s == 'text': formats.append('autotext') # only include if some formats were defined (even empty ones would end up with autotext...) if len(formats) > 1: formats.append('raw') templates[name] = { 'name': name, 'has_handler': name in dir(handlers), 'formats': formats, } return HttpResponse( render_to_string( 'template_preview_list.jinja2', {'templates': sorted(templates.values(), key=lambda t: t['name']) }))
def get_template(self, uri): try: return super(AppTemplateLookup, self).get_template(uri) except TopLevelLookupException as e: if not hasattr(self, "app_dirs"): from django.template.utils import get_app_template_dirs setattr(self, "app_dirs", get_app_template_dirs("templates")) u = re.sub(r'^\/+', '', uri) for dir in self.app_dirs: dir = dir.replace(os.path.sep, posixpath.sep) srcfile = posixpath.normpath(posixpath.join(dir, u)) if os.path.isfile(srcfile): return self._load(srcfile, uri) else: raise TopLevelLookupException("Cant locate template for uri %r" % uri)
def get_template(self, uri): try: return super(AppTemplateLookup, self).get_template(uri) except TopLevelLookupException: if not hasattr(self, "app_dirs"): from django.template.utils import get_app_template_dirs setattr(self, "app_dirs", get_app_template_dirs("templates")) u = re.sub(r'^\/+', '', uri) for dir in self.app_dirs: dir = dir.replace(os.path.sep, posixpath.sep) srcfile = posixpath.normpath(posixpath.join(dir, u)) if os.path.isfile(srcfile): return self._load(srcfile, uri) else: raise TopLevelLookupException("Cant locate template for uri %r" % uri)
def schedule_template_directories(self, settings, event_handler): template_engines = getattr(settings, 'TEMPLATES', []) if not template_engines: self.logger.info( f'No template engines defined in TEMPLATES settings variable.') for template_engine in template_engines: app_dirs_enabled = template_engine.get('APP_DIRS', False) if app_dirs_enabled: template_directories = template_utilities.get_app_template_dirs( 'templates') else: template_directories = template_engine.get('DIRS', []) for template_directory in template_directories: self.schedule(event_handler, template_directory)
def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons. """ if not template_dirs: template_dirs = get_app_template_dirs('templates') site_skin = get_site_skin(site=Site.objects.get_current(), name=settings.SKIN_NAME) if site_skin is not None: for template_dir in template_dirs: try: yield safe_join(template_dir, site_skin.path, template_name) except SuspiciousFileOperation: # The joined path was located outside of this template_dir # (it might be inside another one, so this isn't fatal). pass else: pass
def get_django_template_dirs(loader_list=None): """Build a list of template directories based on configured loaders. """ if not loader_list: loader_list = settings.TEMPLATE_LOADERS template_dirs = [] for loader in loader_list: if loader in FILESYSTEM_LOADERS: template_dirs.extend(settings.TEMPLATE_DIRS) if loader in APPDIR_LOADERS: from django.template.utils import get_app_template_dirs template_dirs.extend(get_app_template_dirs('templates')) if isinstance(loader, (list, tuple)) and len(loader) >= 2: # The cached loader uses the tuple syntax, but simply search all # tuples for nested loaders; thus possibly support custom ones too. template_dirs.extend(get_django_template_dirs(loader[1])) return uniq(template_dirs)
def get_template_sources(self, template_name, template_dirs=None): """ Same as `AppDirectoriesLoader.get_template_sources` but apps in TEMPLATE_APP_DIRS_BLACK_LIST will not have it's templates loaded. """ if not template_dirs: template_dirs = get_app_template_dirs('templates') template_dirs = list(template_dirs) for app, tmpl_dir in product(settings.TEMPLATE_APP_DIRS_BLACK_LIST, template_dirs): if '%s/templates' % app in tmpl_dir and tmpl_dir in template_dirs: template_dirs.remove(tmpl_dir) template_dirs = tuple(template_dirs) for template_dir in template_dirs: try: yield safe_join(template_dir, template_name) except SuspiciousFileOperation: # The joined path was located outside of this template_dir # (it might be inside another one, so this isn't fatal). pass
def get_dirs(self): return get_app_template_dirs('templates')
# Since this package contains a "django" module, this is required on Python 2.
def get_dirs(self): return get_app_template_dirs(persist_settings.APP_DOCUMENT_DIR)
def get_dirs(self): # TODO 此返回值是元组,里面都是绝对路径: # (PosixPath('.../site-packages/django/contrib/admin/templates'), # PosixPath('.../site-packages/django/contrib/auth/templates'), # PosixPath('.../qa_community/home/templates')) return get_app_template_dirs('templates')
func = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a "%s" callable request processor' % (module, attr)) _hooks.append(func) TEMPLATESADMIN_EDITHOOKS = tuple(_hooks) _fixpath = lambda path: os.path.abspath(os.path.normpath(path)) # Load all templates (recursively) TEMPLATESADMIN_TEMPLATE_DIRS = getattr( settings, 'TEMPLATESADMIN_TEMPLATE_DIRS', [ d for d in list(dir for template_engine in settings.TEMPLATES for dir in template_engine.get('DIRS') ) + \ list(get_app_template_dirs('templates')) if os.path.isdir(d) ] ) TEMPLATESADMIN_TEMPLATE_DIRS = [_fixpath(dir) for dir in TEMPLATESADMIN_TEMPLATE_DIRS] def user_in_templatesadmin_group(user): try: user.is_superuser or user.groups.get(name=TEMPLATESADMIN_GROUP) return True except ObjectDoesNotExist: return False @never_cache @login_required @user_passes_test(lambda u: user_in_templatesadmin_group(u)) def listing(request,
def get_dirs(self): """ Same as core function """ return get_app_template_dirs('templates')
except ImportError: from django import get_version django_version = get_version() from django.utils._os import safe_join from django.template.base import TemplateDoesNotExist from django.template.loaders.filesystem import Loader as BaseLoader django_version = float('.'.join(django_version.split('.')[:2])) is_django_18 = django_version == 1.8 if is_django_18: from django.template.utils import get_app_template_dirs from django.template.loaders.app_directories import ( Loader as AppsBaseLoader) app_template_dirs = get_app_template_dirs('templates') else: from django.template.loaders.app_directories import ( Loader as AppsBaseLoader, app_template_dirs) from django_vest.config import settings __ALL__ = ('Loader', 'AppsLoader') DJANGO_ORIGIN = 'DJANGO_ORIGIN/' class ThemeLoaderMixin(object): """ Adding ability for work with themes.
# coding: utf-8 from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import from __future__ import division from django.template.loaders.app_directories import Loader as BaseLoader try: # Django 1.7x or older from django.template.loaders.app_directories import app_template_dirs except ImportError: # Django 1.8 from django.template.utils import get_app_template_dirs app_template_dirs = get_app_template_dirs("templates") from .base import DomainLoaderMixin class Loader(DomainLoaderMixin, BaseLoader): """ get_template_sources looks in the saved request object from the middleware for directories and passes back the path. Doesn't verify that the path is valid, though. """ default_template_dirs = app_template_dirs
def get_dirs(self): template_dirs = list(get_app_template_dirs('templates')) return tuple(reversed(template_dirs))
def get_dirs(self): return get_app_template_dirs("templates")
def get_template_sources(self, template_name, template_dirs=None): if not template_dirs: template_dirs = list(get_app_template_dirs('templates')) template_dirs = tuple(reversed(template_dirs)) return super().get_template_sources(template_name, template_dirs=template_dirs)
from django.core.management.base import CommandError, BaseCommand from django.template.utils import get_app_template_dirs from django.template.loader import _engine_list try: from django.utils.six import input as raw_input except ImportError: pass from dbtemplates.models import Template ALWAYS_ASK, FILES_TO_DATABASE, DATABASE_TO_FILES = ('0', '1', '2') DIRS = [] for engine in _engine_list(): DIRS.extend(engine.dirs) app_template_dirs = get_app_template_dirs('templates') class Command(BaseCommand): help = "Syncs file system templates with the database bidirectionally." def add_arguments(self, parser): parser.add_argument("-e", "--ext", dest="ext", action="store", default="html", help="extension of the files you want to " "sync with the database [default: %default]") parser.add_argument("-f", "--force",
raise ImproperlyConfigured( 'Module "%s" does not define a "%s" callable request processor' % (module, attr)) _hooks.append(func) TEMPLATESADMIN_EDITHOOKS = tuple(_hooks) _fixpath = lambda path: os.path.abspath(os.path.normpath(path)) # Load all templates (recursively) TEMPLATESADMIN_TEMPLATE_DIRS = getattr( settings, 'TEMPLATESADMIN_TEMPLATE_DIRS', [ d for d in list(dir for template_engine in settings.TEMPLATES for dir in template_engine.get('DIRS') ) + \ list(get_app_template_dirs('templates')) if os.path.isdir(d) ] ) TEMPLATESADMIN_TEMPLATE_DIRS = [ _fixpath(dir) for dir in TEMPLATESADMIN_TEMPLATE_DIRS ] def user_in_templatesadmin_group(user): try: user.is_superuser or user.groups.get(name=TEMPLATESADMIN_GROUP) return True except ObjectDoesNotExist: return False
"""