Exemplo n.º 1
0
def capture(context, callable_, *args, **kwargs):
    """execute the given template def, capturing the output into a buffer."""
    if not callable(callable_):
        raise exceptions.RuntimeException("capture() function expects a callable as its argument (i.e. capture(func, *args, **kwargs))")
    context._push_buffer()
    try:
        callable_(*args, **kwargs)
    finally:
        buf = context._pop_buffer()
    return buf.getvalue()
Exemplo n.º 2
0
 def __init__(self, cache):
     if not has_beaker:
         raise exceptions.RuntimeException(
             "Can't initialize Beaker plugin; Beaker is not installed.")
     global _beaker_cache
     if _beaker_cache is None:
         if 'manager' in cache.template.cache_args:
             _beaker_cache = cache.template.cache_args['manager']
         else:
             _beaker_cache = beaker_cache.CacheManager()
     super(BeakerCacheImpl, self).__init__(cache)
Exemplo n.º 3
0
 def load(self, name):
     if name in self.impls:
         return self.impls[name]()
     else:
         import pkg_resources
         for impl in pkg_resources.iter_entry_points(self.group, name):
             self.impls[name] = impl.load
             return impl.load()
         else:
             raise exceptions.RuntimeException("Can't load plugin %s %s" %
                                               (self.group, name))
Exemplo n.º 4
0
    def __init__(self, cache):
        global _beaker_cache
        if _beaker_cache is None:
            try:
                from beaker import cache as beaker_cache
            except ImportError, e:
                raise exceptions.RuntimeException(
                    "the Beaker package is required to use cache "
                    "functionality.")

            _beaker_cache = beaker_cache.CacheManager()
Exemplo n.º 5
0
 def _get_cache(self, defname, type=None, **kw):
     if not cache:
         raise exceptions.RuntimeException("the Beaker package is required to use cache functionality.")
     if type == 'memcached':
         type = 'ext:memcached'
     if not type:
         (type, kw) = self.def_regions.get(defname, ('memory', {}))
     else:
         self.def_regions[defname] = (type, kw)
     return cache.get_cache(self.id, type=type, **kw)
     
Exemplo n.º 6
0
    def load(self, name):
        if name in self.impls:
            return self.impls[name]()

        for impl in importlib_metadata_get(self.group):
            if impl.name == name:
                self.impls[name] = impl.load
                return impl.load()

        from mako import exceptions

        raise exceptions.RuntimeException("Can't load plugin %s %s" %
                                          (self.group, name))
Exemplo n.º 7
0
    def __init__(self, cache):
        global _beaker_cache
        if _beaker_cache is None:
            try:
                from beaker import cache as beaker_cache
            except ImportError, e:
                raise exceptions.RuntimeException(
                    "the Beaker package is required to use cache "
                    "functionality.")

            if 'manager' in cache.template.cache_args:
                _beaker_cache = cache.template.cache_args['manager']
            else:
                _beaker_cache = beaker_cache.CacheManager()
Exemplo n.º 8
0
    def __getattr__(self, key):
        if self.callables and key in self.callables:
            return self.callables[key]

        if self.template and self.template.has_def(key):
            callable_ = self.template.get_def(key).callable_
            return lambda *args, **kwargs:callable_(self.context, *args, **kwargs)

        if self._module and hasattr(self._module, key):
            callable_ = getattr(self._module, key)
            return lambda *args, **kwargs:callable_(self.context, *args, **kwargs)

        if self.inherits is not None:
            return getattr(self.inherits, key)
        raise exceptions.RuntimeException("Namespace '%s' has no member '%s'" % (self.name, key))
Exemplo n.º 9
0
 def _get_container(self, key, type, **kwargs):
     try:
         return self._containers[key]
     except KeyError:
         if container is None:
             raise exceptions.RuntimeException(
                 "the Beaker package is required to use cache functionality."
             )
         kw = self.kwargs.copy()
         kw.update(kwargs)
         return self._containers.setdefault(
             key, clsmap[type](key,
                               self.context,
                               self.id,
                               starttime=self.starttime,
                               **kw))
Exemplo n.º 10
0
def capture(context, callable_, *args, **kwargs):
    """Execute the given template def, capturing the output into
    a buffer.

    See the example in :ref:`namespaces_python_modules`.

    """

    if not callable(callable_):
        raise exceptions.RuntimeException(
            "capture() function expects a callable as "
            "its argument (i.e. capture(func, *args, **kwargs))")
    context._push_buffer()
    try:
        callable_(*args, **kwargs)
    finally:
        buf = context._pop_buffer()
    return buf.getvalue()
Exemplo n.º 11
0
 def __getattr__(self, key):
     if self.callables is not None:
         try:
             return self.callables[key]
         except KeyError:
             pass
     if self.template is not None:
         try:
             callable_ = self.template.get_def(key).callable_
             return lambda *args, **kwargs: callable_(
                 self.context, *args, **kwargs)
         except AttributeError:
             pass
     if self._module is not None:
         try:
             callable_ = getattr(self._module, key)
             return lambda *args, **kwargs: callable_(
                 self.context, *args, **kwargs)
         except AttributeError:
             pass
     if self.inherits is not None:
         return getattr(self.inherits, key)
     raise exceptions.RuntimeException("Namespace '%s' has no member '%s'" %
                                       (self.name, key))
Exemplo n.º 12
0
    def __init__(self, 
                    text=None, 
                    filename=None, 
                    uri=None, 
                    format_exceptions=False, 
                    error_handler=None, 
                    lookup=None, 
                    output_encoding=None, 
                    encoding_errors='strict', 
                    module_directory=None, 
                    cache_type=None, 
                    cache_dir=None, 
                    cache_url=None, 
                    module_filename=None, 
                    input_encoding=None, 
                    disable_unicode=False, 
                    default_filters=None, 
                    buffer_filters=(), 
                    imports=None, 
                    preprocessor=None, 
                    cache_enabled=True):
        """Construct a new Template instance using either literal template
        text, or a previously loaded template module
        
        :param text: textual template source, or None if a module is to be
            provided
        
        :param uri: the uri of this template, or some identifying string.
            defaults to the full filename given, or "memory:(hex id of this
            Template)" if no filename
        
        :param filename: filename of the source template, if any
        
        :param format_exceptions: catch exceptions and format them into an
            error display template
        """
        
        if uri:
            self.module_id = re.sub(r'\W', "_", uri)
            self.uri = uri
        elif filename:
            self.module_id = re.sub(r'\W', "_", filename)
            drive, path = os.path.splitdrive(filename)
            path = os.path.normpath(path).replace(os.path.sep, "/")
            self.uri = path
        else:
            self.module_id = "memory:" + hex(id(self))
            self.uri = self.module_id
        
        self.input_encoding = input_encoding
        self.output_encoding = output_encoding
        self.encoding_errors = encoding_errors
        self.disable_unicode = disable_unicode

        if util.py3k and disable_unicode:
            raise exceptions.UnsupportedError(
                                    "Mako for Python 3 does not "
                                    "support disabling Unicode")
        
        if default_filters is None:
            if util.py3k or self.disable_unicode:
                self.default_filters = ['str']
            else:
                self.default_filters = ['unicode']
        else:
            self.default_filters = default_filters
        self.buffer_filters = buffer_filters
            
        self.imports = imports
        self.preprocessor = preprocessor
        
        # if plain text, compile code in memory only
        if text is not None:
            (code, module) = _compile_text(self, text, filename)
            self._code = code
            self._source = text
            ModuleInfo(module, None, self, filename, code, text)
        elif filename is not None:
            # if template filename and a module directory, load
            # a filesystem-based module file, generating if needed
            if module_filename is not None:
                path = module_filename
            elif module_directory is not None:
                u = self.uri
                if u[0] == '/':
                    u = u[1:]
                path = os.path.abspath(
                        os.path.join(
                            os.path.normpath(module_directory), 
                            os.path.normpath(u) + ".py"
                            )
                        )
            else:
                path = None
                
            module = self._compile_from_file(path, filename)
        else:
            raise exceptions.RuntimeException(
                                "Template requires text or filename")

        self.module = module
        self.filename = filename
        self.callable_ = self.module.render_body
        self.format_exceptions = format_exceptions
        self.error_handler = error_handler
        self.lookup = lookup
        self.cache_type = cache_type
        self.cache_dir = cache_dir
        self.cache_url = cache_url
        self.cache_enabled = cache_enabled
Exemplo n.º 13
0
    def __init__(
        self,
        text=None,
        filename=None,
        uri=None,
        format_exceptions=False,
        error_handler=None,
        lookup=None,
        output_encoding=None,
        encoding_errors="strict",
        module_directory=None,
        cache_args=None,
        cache_impl="beaker",
        cache_enabled=True,
        cache_type=None,
        cache_dir=None,
        cache_url=None,
        module_filename=None,
        input_encoding=None,
        disable_unicode=False,
        module_writer=None,
        bytestring_passthrough=False,
        default_filters=None,
        buffer_filters=(),
        strict_undefined=False,
        imports=None,
        future_imports=None,
        enable_loop=True,
        preprocessor=None,
        lexer_cls=None,
        include_error_handler=None,
    ):
        if uri:
            self.module_id = re.sub(r"\W", "_", uri)
            self.uri = uri
        elif filename:
            self.module_id = re.sub(r"\W", "_", filename)
            drive, path = os.path.splitdrive(filename)
            path = os.path.normpath(path).replace(os.path.sep, "/")
            self.uri = path
        else:
            self.module_id = "memory:" + hex(id(self))
            self.uri = self.module_id

        u_norm = self.uri
        if u_norm.startswith("/"):
            u_norm = u_norm[1:]
        u_norm = os.path.normpath(u_norm)
        if u_norm.startswith(".."):
            raise exceptions.TemplateLookupException(
                'Template uri "%s" is invalid - '
                "it cannot be relative outside "
                "of the root path." % self.uri)

        self.input_encoding = input_encoding
        self.output_encoding = output_encoding
        self.encoding_errors = encoding_errors
        self.disable_unicode = disable_unicode
        self.bytestring_passthrough = bytestring_passthrough or disable_unicode
        self.enable_loop = enable_loop
        self.strict_undefined = strict_undefined
        self.module_writer = module_writer

        if compat.py3k and disable_unicode:
            raise exceptions.UnsupportedError("Mako for Python 3 does not "
                                              "support disabling Unicode")
        elif output_encoding and disable_unicode:
            raise exceptions.UnsupportedError(
                "output_encoding must be set to "
                "None when disable_unicode is used.")
        if default_filters is None:
            if compat.py3k or self.disable_unicode:
                self.default_filters = ["str"]
            else:
                self.default_filters = ["unicode"]
        else:
            self.default_filters = default_filters
        self.buffer_filters = buffer_filters

        self.imports = imports
        self.future_imports = future_imports
        self.preprocessor = preprocessor

        if lexer_cls is not None:
            self.lexer_cls = lexer_cls

        # if plain text, compile code in memory only
        if text is not None:
            (code, module) = _compile_text(self, text, filename)
            self._code = code
            self._source = text
            ModuleInfo(module, None, self, filename, code, text)
        elif filename is not None:
            # if template filename and a module directory, load
            # a filesystem-based module file, generating if needed
            if module_filename is not None:
                path = module_filename
            elif module_directory is not None:
                path = os.path.abspath(
                    os.path.join(os.path.normpath(module_directory),
                                 u_norm + ".py"))
            else:
                path = None
            module = self._compile_from_file(path, filename)
        else:
            raise exceptions.RuntimeException(
                "Template requires text or filename")

        self.module = module
        self.filename = filename
        self.callable_ = self.module.render_body
        self.format_exceptions = format_exceptions
        self.error_handler = error_handler
        self.include_error_handler = include_error_handler
        self.lookup = lookup

        self.module_directory = module_directory

        self._setup_cache_args(
            cache_impl,
            cache_enabled,
            cache_args,
            cache_type,
            cache_dir,
            cache_url,
        )
Exemplo n.º 14
0
    def __init__(self,
                 text=None,
                 filename=None,
                 uri=None,
                 format_exceptions=False,
                 error_handler=None,
                 lookup=None,
                 output_encoding=None,
                 encoding_errors='strict',
                 module_directory=None,
                 cache_type=None,
                 cache_dir=None,
                 cache_url=None,
                 module_filename=None,
                 input_encoding=None,
                 disable_unicode=False,
                 bytestring_passthrough=False,
                 default_filters=None,
                 buffer_filters=(),
                 strict_undefined=False,
                 imports=None,
                 preprocessor=None,
                 cache_enabled=True):
        if uri:
            self.module_id = re.sub(r'\W', "_", uri)
            self.uri = uri
        elif filename:
            self.module_id = re.sub(r'\W', "_", filename)
            drive, path = os.path.splitdrive(filename)
            path = os.path.normpath(path).replace(os.path.sep, "/")
            self.uri = path
        else:
            self.module_id = "memory:" + hex(id(self))
            self.uri = self.module_id

        self.input_encoding = input_encoding
        self.output_encoding = output_encoding
        self.encoding_errors = encoding_errors
        self.disable_unicode = disable_unicode
        self.bytestring_passthrough = bytestring_passthrough or disable_unicode
        self.strict_undefined = strict_undefined

        if util.py3k and disable_unicode:
            raise exceptions.UnsupportedError("Mako for Python 3 does not "
                                              "support disabling Unicode")
        elif output_encoding and disable_unicode:
            raise exceptions.UnsupportedError(
                "output_encoding must be set to "
                "None when disable_unicode is used.")
        if default_filters is None:
            if util.py3k or self.disable_unicode:
                self.default_filters = ['str']
            else:
                self.default_filters = ['unicode']
        else:
            self.default_filters = default_filters
        self.buffer_filters = buffer_filters

        self.imports = imports
        self.preprocessor = preprocessor

        # if plain text, compile code in memory only
        if text is not None:
            (code, module) = _compile_text(self, text, filename)
            self._code = code
            self._source = text
            ModuleInfo(module, None, self, filename, code, text)
        elif filename is not None:
            # if template filename and a module directory, load
            # a filesystem-based module file, generating if needed
            if module_filename is not None:
                path = module_filename
            elif module_directory is not None:
                u = self.uri
                if u[0] == '/':
                    u = u[1:]
                path = os.path.abspath(
                    os.path.join(os.path.normpath(module_directory),
                                 os.path.normpath(u) + ".py"))
            else:
                path = None

            module = self._compile_from_file(path, filename)
        else:
            raise exceptions.RuntimeException(
                "Template requires text or filename")

        self.module = module
        self.filename = filename
        self.callable_ = self.module.render_body
        self.format_exceptions = format_exceptions
        self.error_handler = error_handler
        self.lookup = lookup
        self.cache_type = cache_type
        self.cache_dir = cache_dir
        self.cache_url = cache_url
        self.cache_enabled = cache_enabled
Exemplo n.º 15
0
    def __init__(self, text=None, filename=None, uri=None, format_exceptions=False, error_handler=None, 
        lookup=None, output_encoding=None, encoding_errors='strict', module_directory=None, cache_type=None, 
        cache_dir=None, cache_url=None, module_filename=None, input_encoding=None, disable_unicode=False, default_filters=None, 
        buffer_filters=[], imports=None, preprocessor=None, cache_enabled=True):
        """construct a new Template instance using either literal template text, or a previously loaded template module
        
        text - textual template source, or None if a module is to be provided
        
        uri - the uri of this template, or some identifying string. defaults to the 
        full filename given, or "memory:(hex id of this Template)" if no filename
        
        filename - filename of the source template, if any
        
        format_exceptions - catch exceptions and format them into an error display template
        """
        
        if uri:
            self.module_id = re.sub(r'\W', "_", uri)
            self.uri = uri
        elif filename:
            self.module_id = re.sub(r'\W', "_", filename)
            self.uri = filename
        else:
            self.module_id = "memory:" + hex(id(self))
            self.uri = self.module_id
        
        self.input_encoding = input_encoding
        self.output_encoding = output_encoding
        self.encoding_errors = encoding_errors
        self.disable_unicode = disable_unicode
        if default_filters is None:
            if self.disable_unicode:
                self.default_filters = ['str']
            else:
                self.default_filters = ['unicode']
        else:
            self.default_filters = default_filters
        self.buffer_filters = buffer_filters
            
        self.imports = imports
        self.preprocessor = preprocessor
        
        # if plain text, compile code in memory only
        if text is not None:
            (code, module) = _compile_text(self, text, filename)
            self._code = code
            self._source = text
            ModuleInfo(module, None, self, filename, code, text)
        elif filename is not None:
            # if template filename and a module directory, load
            # a filesystem-based module file, generating if needed
            if module_filename is not None:
                path = module_filename
            elif module_directory is not None:
                u = self.uri
                if u[0] == '/':
                    u = u[1:]
                path = os.path.abspath(os.path.join(module_directory.replace('/', os.path.sep), u + ".py"))
            else:
                path = None    
            if path is not None:
                util.verify_directory(os.path.dirname(path))
                filemtime = os.stat(filename)[stat.ST_MTIME]
                if not os.path.exists(path) or os.stat(path)[stat.ST_MTIME] < filemtime:
                    _compile_module_file(self, file(filename).read(), filename, path)
                module = imp.load_source(self.module_id, path, file(path))
                del sys.modules[self.module_id]
                if module._magic_number != codegen.MAGIC_NUMBER:
                    _compile_module_file(self, file(filename).read(), filename, path)
                    module = imp.load_source(self.module_id, path, file(path))
                    del sys.modules[self.module_id]
                ModuleInfo(module, path, self, filename, None, None)
            else:
                # template filename and no module directory, compile code
                # in memory
                (code, module) = _compile_text(self, file(filename).read(), filename)
                self._source = None
                self._code = code
                ModuleInfo(module, None, self, filename, code, None)
        else:
            raise exceptions.RuntimeException("Template requires text or filename")

        self.module = module
        self.filename = filename
        self.callable_ = self.module.render_body
        self.format_exceptions = format_exceptions
        self.error_handler = error_handler
        self.lookup = lookup
        self.cache_type = cache_type
        self.cache_dir = cache_dir
        self.cache_url = cache_url
        self.cache_enabled = cache_enabled
Exemplo n.º 16
0
 def get_cache(self, name, **kwargs):
     raise exceptions.RuntimeException(
         "the Beaker package is required to use cache functionality.")
Exemplo n.º 17
0
 def __getattr__(self, key):
     raise exceptions.RuntimeException("No loop context is established")