<s> import os <EOL> from collections import Counter , OrderedDict <EOL> from django . apps import apps <EOL> from django . conf import settings <EOL> from django . core . exceptions import ImproperlyConfigured <EOL> from django . utils import lru_cache <EOL> from django . utils . _os import upath <EOL> from django . utils . functional import cached_property <EOL> from django . utils . module_loading import import_string <EOL> class InvalidTemplateEngineError ( ImproperlyConfigured ) : <EOL> pass <EOL> class EngineHandler ( object ) : <EOL> def __init__ ( self , templates = None ) : <EOL> """<STR_LIT>""" <EOL> self . _templates = templates <EOL> self . _engines = { } <EOL> @ cached_property <EOL> def templates ( self ) : <EOL> if self . _templates is None : <EOL> self . _templates = settings . TEMPLATES <EOL> templates = OrderedDict ( ) <EOL> backend_names = [ ] <EOL> for tpl in self . _templates : <EOL> tpl = tpl . copy ( ) <EOL> try : <EOL> default_name = tpl [ '<STR_LIT>' ] . rsplit ( '<STR_LIT:.>' , <NUM_LIT:2> ) [ - <NUM_LIT:2> ] <EOL> except Exception : <EOL> invalid_backend = tpl . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> raise ImproperlyConfigured ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" . format ( invalid_backend ) ) <EOL> tpl . setdefault ( '<STR_LIT>' , default_name ) <EOL> tpl . setdefault ( '<STR_LIT>' , [ ] ) <EOL> tpl . setdefault ( '<STR_LIT>' , False ) <EOL> tpl . setdefault ( '<STR_LIT>' , { } ) <EOL> templates [ tpl [ '<STR_LIT>' ] ] = tpl <EOL> backend_names . append ( tpl [ '<STR_LIT>' ] ) <EOL> counts = Counter ( backend_names ) <EOL> duplicates = [ alias for alias , count in counts . most_common ( ) if count > <NUM_LIT:1> ] <EOL> if duplicates : <EOL> raise ImproperlyConfigured ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> . format ( "<STR_LIT:U+002CU+0020>" . join ( duplicates ) ) ) <EOL> return templates <EOL> def __getitem__ ( self , alias ) : <EOL> try : <EOL> return self . _engines [ alias ] <EOL> except KeyError : <EOL> try : <EOL> params = self . templates [ alias ] <EOL> except KeyError : <EOL> raise InvalidTemplateEngineError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" . format ( alias ) ) <EOL> params = params . copy ( ) <EOL> backend = params . pop ( '<STR_LIT>' ) <EOL> engine_cls = import_string ( backend ) <EOL> engine = engine_cls ( params ) <EOL> self . _engines [ alias ] = engine <EOL> return engine <EOL> def __iter__ ( self ) : <EOL> return iter ( self . templates ) <EOL> def all ( self ) : <EOL> return [ self [ alias ] for alias in self ] <EOL> @ lru_cache . lru_cache ( ) <EOL> def get_app_template_dirs ( dirname ) : <EOL> """<STR_LIT>""" <EOL> template_dirs = [ ] <EOL> for app_config in apps . get_app_configs ( ) : <EOL> if not app_config . path : <EOL> continue <EOL> template_dir = os . path . join ( app_config . path , dirname ) <EOL> if os . path . isdir ( template_dir ) : <EOL> template_dirs . append ( upath ( template_dir ) ) <EOL> return tuple ( template_dirs ) </s>
