예제 #1
0
def get_django_filter(django_filter, load='django'):

    if django.VERSION < (1, 9):
        from django.template.base import get_library
        if load and not load == 'django':
            library = get_library(load)
        else:
            library_path = 'django.template.defaultfilters'
            if django.VERSION > (1, 8):
                from django.template.base import import_library
                library = import_library(library_path)
            else:
                from django.template import import_library
                library = import_library(library_path)

    else:
        from django.template.backends.django import get_installed_libraries
        from django.template.library import import_library
        libraries = get_installed_libraries()
        if load and not load == 'django':
            library_path = libraries.get(load)
            if not library_path:
                raise Exception('templatetag "{}" is not registered'.format(load))
        else:
            library_path = 'django.template.defaultfilters'

        library = import_library(library_path)
    filter_method = library.filters.get(django_filter)
    if not filter_method:
        raise Exception('filter "{}" not exist on {} templatetag package'.format(
            django_filter, load
        ))

    return filter_method
예제 #2
0
def get_django_filter(django_filter, load='django'):

    if django.VERSION < (1, 9):
        from django.template.base import get_library
        if load and not load == 'django':
            library = get_library(load)
        else:
            library_path = 'django.template.defaultfilters'
            if django.VERSION > (1, 8):
                from django.template.base import import_library
                library = import_library(library_path)
            else:
                from django.template import import_library
                library = import_library(library_path)

    else:
        from django.template.backends.django import get_installed_libraries
        from django.template.library import import_library
        libraries = get_installed_libraries()
        if load and not load == 'django':
            library_path = libraries.get(load)
            if not library_path:
                raise Exception(
                    'templatetag "{}" is not registered'.format(load))
        else:
            library_path = 'django.template.defaultfilters'

        library = import_library(library_path)
    filter_method = library.filters.get(django_filter)
    if not filter_method:
        raise Exception(
            'filter "{}" not exist on {} templatetag package'.format(
                django_filter, load))

    return filter_method
예제 #3
0
 def get_templatetag_libraries(custom_libraries):
     """
     Return a collation of template tag libraries from installed
     applications and the supplied custom_libraries argument.
     """
     #pylint: disable=no-name-in-module,import-error
     from django.template.backends.django import get_installed_libraries
     libraries = get_installed_libraries()
     libraries.update(custom_libraries)
     return libraries
예제 #4
0
def load_tag_library(libname):
    """Load a templatetag library on multiple Django versions.

    Returns None if the library isn't loaded.
    """
    from django.template.backends.django import get_installed_libraries
    from django.template.library import InvalidTemplateLibrary
    try:
        lib = get_installed_libraries()[libname]
        lib = importlib.import_module(lib).register
        return lib
    except (InvalidTemplateLibrary, KeyError):
        return None
예제 #5
0
    def django_init(self):
        '''
        Initializes the django engine. The root must have been set already."
        '''

        elems = os.path.split(self.root)[:-1]
        parent = os.path.join(*elems)
        sys.path.append(parent)

        BASE_APP = []
        try:
            # Attempt to import the root folder. This is necessary to access
            # the local templatetag libraries.
            base = os.path.split(self.root)[-1]
            logger.debug("importing app: %s" % base)
            importlib.import_module(base)
            BASE_APP = [base]
        except ImportError as exc:
            logger.debug("app '{}' cannot be imported: {}".format(base, exc))

        TEMPLATE_DIR = join(os.path.dirname(__file__), "templates")
        dirs = [self.root, join(self.root, 'templates'), TEMPLATE_DIR]
        logger.debug("template dirs: {}".format(dirs))
        settings.configure(
            DEBUG=True,
            TEMPLATE_DEBUG=True,
            TEMPLATES=[{
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'DIRS': dirs,
                'APP_DIRS': True,
                'OPTIONS': {
                    'string_if_invalid':
                    "Undefined: %s ",
                    'builtins': [
                        'pyblue.templatetags.pytags',
                        'django.contrib.humanize.templatetags.humanize',
                    ],
                }
            }],
            INSTALLED_APPS=[
                "pyblue", "django.contrib.humanize",
                "django.contrib.staticfiles"
            ] + BASE_APP,
            STATIC_URL='/static/',
        )
        django.setup()

        logger.debug("templatetags: %s" % ", ".join(get_installed_libraries()))
예제 #6
0
파일: engine.py 프로젝트: Njlaa/pyblue
    def django_init(self):
        '''
        Initializes the django engine. The root must have been set already."
        '''

        elems = os.path.split(self.root)[:-1]
        parent = os.path.join(*elems)
        sys.path.append(parent)

        BASE_APP = []
        try:
            # Attempt to import the root folder. This is necessary to access
            # the local templatetag libraries.
            base = os.path.split(self.root)[-1]
            logger.debug("importing app: %s" % base)
            importlib.import_module(base)
            BASE_APP = [ base ]
        except ImportError as exc:
            logger.debug("app '{}' cannot be imported: {}".format(base, exc))

        TEMPLATE_DIR = join(os.path.dirname(__file__), "templates")
        dirs = [self.root, join(self.root, 'templates'), TEMPLATE_DIR]
        logger.debug("template dirs: {}".format(dirs))
        settings.configure(
            DEBUG=True, TEMPLATE_DEBUG=True,
            TEMPLATES=[
                {
                    'BACKEND': 'django.template.backends.django.DjangoTemplates',
                    'DIRS': dirs,
                    'APP_DIRS': True,
                    'OPTIONS': {
                        'string_if_invalid': "Undefined: %s ",
                        'builtins': [
                            'pyblue.templatetags.pytags',
                            'django.contrib.humanize.templatetags.humanize',
                        ],
                    }
                }
            ],
            INSTALLED_APPS=["pyblue", "django.contrib.humanize",
                            "django.contrib.staticfiles"] + BASE_APP,

            STATIC_URL='/static/',
        )
        django.setup()

        logger.debug("templatetags: %s" % ", ".join(get_installed_libraries()))
예제 #7
0
def template_tag_library(name):
    from importlib import import_module
    from django.template.backends.django import get_installed_libraries

    libs = get_installed_libraries()

    if name not in libs:
        raise ValueError(f'template tag library {name} not found')

    mod = import_module(libs[name])

    if not mod.__file__.startswith(ROOT_DIR):
        raise ValueError(f'template tag library {name} is not in project')

    url = github_url_for_path(os.path.relpath(mod.__file__, ROOT_DIR))

    return SafeString(f'<code><a href="{url}">{name}</a></code>')
예제 #8
0
파일: styleguide.py 프로젝트: zspencer/calc
def get_template_tag_library_and_url(name):
    '''
    Return a tuple containing the Python module for the given template tag
    library, and the GitHub URL to its source code.
    '''

    libs = get_installed_libraries()

    if name not in libs:
        raise ValueError(f'template tag library {name} not found')

    mod = import_module(libs[name])

    if not mod.__file__.startswith(ROOT_DIR):
        raise ValueError(f'template tag library {name} is not in project')

    url = github_url_for_path(os.path.relpath(mod.__file__, ROOT_DIR))

    return mod, url
예제 #9
0
파일: styleguide.py 프로젝트: 18F/calc
def get_template_tag_library_and_url(name):
    '''
    Return a tuple containing the Python module for the given template tag
    library, and the GitHub URL to its source code.
    '''

    libs = get_installed_libraries()

    if name not in libs:
        raise ValueError(f'template tag library {name} not found')

    mod = import_module(libs[name])

    if not mod.__file__.startswith(ROOT_DIR):
        raise ValueError(f'template tag library {name} is not in project')

    url = github_url_for_path(os.path.relpath(mod.__file__, ROOT_DIR))

    return mod, url
예제 #10
0
파일: resources.py 프로젝트: lxp20201/lxp
    def render_django_template(self,
                               template_path,
                               context=None,
                               i18n_service=None):
        """
        Evaluate a django template by resource path, applying the provided context.
        """
        context = context or {}
        context['_i18n_service'] = i18n_service
        libraries = {
            'i18n': 'xblockutils.templatetags.i18n',
        }

        # For django 1.8, we have to load the libraries manually, and restore them once the template is rendered.
        _libraries = None
        if django.VERSION[0] == 1 and django.VERSION[1] == 8:
            _libraries = TemplateBase.libraries.copy()
            for library_name in libraries:
                library = TemplateBase.import_library(libraries[library_name])
                if library:
                    TemplateBase.libraries[library_name] = library
            engine = Engine()
        else:
            # Django>1.8 Engine can load the extra templatetag libraries itself
            # but we have to override the default installed libraries.
            from django.template.backends.django import get_installed_libraries
            installed_libraries = get_installed_libraries()
            installed_libraries.update(libraries)
            engine = Engine(libraries=installed_libraries)

        template_str = self.load_unicode(template_path)
        template = Template(template_str, engine=engine)
        rendered = template.render(Context(context))

        # Restore the original TemplateBase.libraries
        if _libraries is not None:
            TemplateBase.libraries = _libraries

        return rendered
예제 #11
0
def get_templatetag_library(module):
    """Get the templatetag module's Library instance.

    Needed for extracting template tags and filters.

    Args:
        module {str}: module's name (e.g. 'app_tags')

    Returns:
        {Library}

    Raises:
        {AttributeError}: nonexistent module
        {InvalidTemplateLibrary}: the module does not have a variable
            named `register`

    """
    try:
        if import_library is not None and get_installed_libraries is not None:
            return import_library(get_installed_libraries().get(module))
        else:
            return get_library(module)
    except (AttributeError, InvalidTemplateLibrary):
        raise
예제 #12
0
    def render_django_template(self, template_path, context=None, i18n_service=None):
        """
        Evaluate a django template by resource path, applying the provided context.
        """
        context = context or {}
        context['_i18n_service'] = i18n_service
        libraries = {
            'i18n': 'xblockutils.templatetags.i18n',
        }

        # For django 1.8, we have to load the libraries manually, and restore them once the template is rendered.
        _libraries = None
        if django.VERSION[0] == 1 and django.VERSION[1] == 8:
            _libraries = TemplateBase.libraries.copy()
            for library_name in libraries:
                library = TemplateBase.import_library(libraries[library_name])
                if library:
                    TemplateBase.libraries[library_name] = library
            engine = Engine()
        else:
            # Django>1.8 Engine can load the extra templatetag libraries itself
            # but we have to override the default installed libraries.
            from django.template.backends.django import get_installed_libraries
            installed_libraries = get_installed_libraries()
            installed_libraries.update(libraries)
            engine = Engine(libraries=installed_libraries)

        template_str = self.load_unicode(template_path)
        template = Template(template_str, engine=engine)
        rendered = template.render(Context(context))

        # Restore the original TemplateBase.libraries
        if _libraries is not None:
            TemplateBase.libraries = _libraries

        return rendered
예제 #13
0
    def django_init(self):
        '''
        Initializes the django engine. The root must have been set already."
        '''

        elems = os.path.split(self.root)[:-1]
        parent = os.path.join(*elems)
        sys.path.append(parent)

        BASE_APP = []
        try:
            # Attempt to import the root folder. This is necessary to access
            # the local templatetag libraries.
            base = os.path.split(self.root)[-1]
            logger.debug("importing app as python module: %s" % base)
            importlib.import_module(base)
            BASE_APP = [base]
        except ImportError as exc:
            logger.debug("app '{}' cannot be imported: {}".format(base, exc))

        # Django Module Settings

        # These templates come with PyBlue
        parent_dir = join(os.path.dirname(__file__), "templates")

        # These templates are in the root folder.
        tmpl_dir = join(self.root, 'templates')

        # Set up more paths via environment variables.
        extra_dir = os.getenv(PYBLUE_EXTRA_DIRS, None)
        extra_dir = extra_dir.split(",") if extra_dir else []

        logger.debug(f"{PYBLUE_EXTRA_DIRS}: {extra_dir}")

        dirs = [self.root, tmpl_dir, parent_dir] + extra_dir

        logger.debug("template dirs: {}".format(dirs))
        settings.configure(
            DEBUG=True, TEMPLATE_DEBUG=True,
            TEMPLATES=[
                {
                    'BACKEND': 'django.template.backends.django.DjangoTemplates',
                    'DIRS': dirs,
                    'APP_DIRS': True,
                    'OPTIONS': {
                        'string_if_invalid': "Undefined: %s ",
                        'builtins': [
                            'pyblue.templatetags.pytags',
                            'django.contrib.humanize.templatetags.humanize',
                        ],
                    }
                }
            ],
            INSTALLED_APPS=["pyblue", "django.contrib.humanize",
                            "django.contrib.staticfiles"] + BASE_APP,

            STATIC_URL='/static/',
        )
        django.setup()

        logger.debug("templatetags: %s" % ", ".join(get_installed_libraries()))
예제 #14
0
 def get_library(libname):
     return get_installed_libraries().get(libname, None)
예제 #15
0
 def get_templatetag_libraries(self, custom_libraries):
     libraries = get_installed_libraries()
     libraries.update(custom_libraries)
     return libraries
예제 #16
0
 def get_installed_libraries():
     for module in tplbackend.get_installed_libraries().values():
         try:
             yield library.import_library(module)
         except (ImproperlyConfigured, library.InvalidTemplateLibrary):
             continue
예제 #17
0
 def get_templatetag_libraries(self, custom_libraries):
     libraries = get_installed_libraries()
     libraries.update(custom_libraries)
     return libraries
예제 #18
0
 def get_installed_libraries():
     for module in tplbackend.get_installed_libraries().values():
         try:
             yield library.import_library(module)
         except (ImproperlyConfigured, library.InvalidTemplateLibrary):
             continue