Ejemplo n.º 1
0
  def throw(self, error, info=None, output=None):
    """Raises a TemplateException.

    This method may be passed an existing TemplateException object; a
    single value containing an error message which is used to instantiate
    a TemplateException of type 'None'; or a pair of values representing
    the exception type and info from which a TemplateException object is
    instantiated.  e.g.

      context.throw(exception)
      context.throw("I'm sorry Dave, I can't do that")
      context.throw('denied', "I'm sorry Dave, I can't do that")

    An optional third parameter can be supplied in the last case which
    is a reference to the current output buffer containing the results
    of processing the template up to the point at which the exception
    was thrown.  The RETURN and STOP directives, for example, use this
    to propagate output back to the user, but it can safely be ignored
    in most cases.
    """
    error = unscalar(error)
    info = unscalar(info)
    if isinstance(error, TemplateException):
      raise error
    elif info is not None:
      raise TemplateException(error, info, output)
    else:
      raise TemplateException("None", error or "", output)
Ejemplo n.º 2
0
def redirect_filter_factory(context, file, options=None):
    outpath = context.config().get("OUTPUT_PATH")
    if not outpath:
        raise TemplateException("redirect", "OUTPUT_PATH is not set")
    if re.search(r"(?:^|/)\.\./", file, re.MULTILINE):
        context.throw("redirect",
                      "relative filenames are not supported: %s" % file)
    if not isinstance(options, dict):
        options = {"binmode": options}

    def redirect_filter(text=""):
        outpath = context.config().get("OUTPUT_PATH")
        if not outpath:
            return ""
        try:
            try:
                os.makedirs(outpath)
            except OSError, e:
                if e.errno != errno.EEXIST:
                    raise
            outpath += "/" + str(file)
            if options.get("binmode"):
                mode = "wb"
            else:
                mode = "w"
            fh = open(outpath, mode)
            fh.write(text)
            fh.close()
        except Exception, e:
            raise TemplateException("redirect", e)
Ejemplo n.º 3
0
def python_filter_factory(context):
    if not context.eval_python():
        raise TemplateException("python", "EVAL_PYTHON is not set")

    def python_filter(text):
        return util.EvaluateCode(str(text), context, context.stash())

    return python_filter
Ejemplo n.º 4
0
 def _parse_error(self, msg, name, text=None):
     """Method used to handle errors encountered during the parse process
 in the _parse() method.
 """
     line = self.line or "unknown"
     if text is not None:
         msg += "\n  [%% %s %%]" % text
     raise TemplateException("parse", "%s line %s: %s" % (name, line, msg))
Ejemplo n.º 5
0
  def format(self, *args):
    """Returns a formatted time/date string for the specified time (or
    the current system time if unspecified) using the format, locale,
    and gmt values specified as arguments or internal values set
    defined at construction time.

    Specifying a true value for gmt will override the local time zone
    and force the output to be for GMT.  Any or all of the arguments
    may be specified as named parameters which get passed as a
    dictionary as the final argument.
    """
    args, params = self._split_arguments(args)
    args = list(args)
    def get(name):
      if args:
        return args.pop(0)
      else:
        return params.get(name) or self.params.get(name)
    time = get("time") or self.now()
    format = get("format") or FORMAT
    locale = get("locale")
    gmt = get("gmt")

    try:
      # If time is numeric, we assume it's seconds since the epoch:
      time = int(time)
    except StandardError:
      # Otherwise, we try to parse it as a 'H:M:S D:M:Y' string:
      date = re.split(r"[-/ :]", str(time))
      if len(date) < 6:
        raise TemplateException(
          "date", "bad time/date string:  expects 'h:m:s d:m:y'  got: '%s'"
          % time)
      date = [str(int(x)) for x in date[:6]]
      date = Time.strptime(" ".join(date), "%H %M %S %d %m %Y")
    else:
      date = GMTIME[bool(gmt)](time)

    if locale is not None:
      old_locale = Locale.setlocale(Locale.LC_ALL)
      try:
        for suffix in ("",) + LOCALE_SUFFIX:
          try_locale = "%s%s" % (locale, suffix)
          try:
            setlocale = Locale.setlocale(Locale.LC_ALL, try_locale)
          except Locale.Error:
            continue
          else:
            if try_locale == setlocale:
              locale = try_locale
              break
        datestr = Time.strftime(format, date)
      finally:
        Locale.setlocale(Locale.LC_ALL, old_locale)
    else:
      datestr = Time.strftime(format, date)

    return datestr
Ejemplo n.º 6
0
def date_locale(time, format, locale):
    date = re.split(r"[-/ :]", time)
    if len(date) < 6:
        return None, TemplateException(
            "date",
            "bad time/date string:  expects 'h:m:s d:m:y'  got: '%s'" % time)
    date = [str(int(x)) for x in date[:6]]
    date = Time.mktime(Time.strptime(" ".join(date), "%H %M %S %d %m %Y"))
    return time_locale(date, format, locale)
Ejemplo n.º 7
0
 def fetch(self, name, args=None, context=None):
     factory = self.__factory[name] = self._load(name, context)
     if not factory:
         return None
     try:
         if isinstance(factory, collections.Callable):
             args = (context, ) + tuple(args or ())
             return factory(*args)
         else:
             raise Error("%s plugin is not callable" % (name, ))
     except Exception as e:
         if self.__tolerant:
             return None
         else:
             raise TemplateException.convert(e)
Ejemplo n.º 8
0
 def fetch(self, name, args=None, context=None):
   factory = self.__factory[name] = self._load(name, context)
   if not factory:
     return None
   try:
     if callable(factory):
       args = (context,) + tuple(args or ())
       return factory(*args)
     else:
       raise Error("%s plugin is not callable" % (name,))
   except Exception, e:
     if self.__tolerant:
       return None
     else:
       raise TemplateException.convert(e)
Ejemplo n.º 9
0
 def redirect_filter(text=""):
   outpath = context.config().get("OUTPUT_PATH")
   if not outpath:
     return ""
   try:
     try:
       os.makedirs(outpath)
     except OSError as e:
       if e.errno != errno.EEXIST:
         raise
     outpath += "/" + str(file)
     if options.get("binmode"):
       mode = "wb"
     else:
       mode = "w"
     fh = open(outpath, mode)
     fh.write(text)
     fh.close()
   except Exception as e:
     raise TemplateException("redirect", e)
   return ""
Ejemplo n.º 10
0
  def catch(self, error, output=None):
    """Called by various directives after catching an exception.

    The first parameter contains the errror which may be a sanitized
    reference to a TemplateException object (such as that raised by the
    throw() method above, a plugin object, and so on) or an error message
    raised from somewhere in user code.  The latter are coerced into
    'None' TemplateException objects.  Like throw() above, the current
    output buffer may be passed as an additional parameter.  As exceptions
    are thrown upwards and outwards from nested blocks, the catch() method
    reconstructs the correct output buffer from these fragments, storing
    it in the exception object for passing further onwards and upwards.  #

    Returns a TemplateException object.
    """
    if isinstance(error, TemplateException):
      if output:
        error.text(output)
      return error
    else:
      return TemplateException("None", error, output)
Ejemplo n.º 11
0
    def __init__(self, config=None):
        config = config or {}
        delim = config.get("DELIMITER", ":")

        # coerce PRE_PROCESS, PROCESS, and POST_PROCESS to lists if necessary,
        # by splitting on non-word characters
        self.__preprocess = Split(config.get("PRE_PROCESS"), delim)
        self.__process = Split(config.get("PROCESS"), delim)
        self.__postprocess = Split(config.get("POST_PROCESS"), delim)
        self.__wrapper = Split(config.get("WRAPPER"), delim)

        # unset PROCESS option unless explicitly specified in config
        if config.get("PROCESS") is None:
            self.__process = None

        self.__error = config.get("ERROR") or config.get("ERRORS")
        self.__autoreset = config.get("AUTO_RESET") is None or \
            config.get("AUTO_RESET")
        self.__debug = config.get("DEBUG", 0) & DEBUG_SERVICE
        self.__context = config.get("CONTEXT") or Config.context(config)
        if not self.__context:
            raise TemplateException()
Ejemplo n.º 12
0
    def fetch(self, name, args, context):
        """Attempts to instantiate or return a filter function named by
        the first parameter, name, with additional constructor arguments
        passed as the second parameter, args.  A reference to the calling
        template.context.Context object is passed as the third paramter.

        Returns a filter function on success or None if the request was
        declined.  Raises a TemplateException on error.
        """
        if not isinstance(name, str):
            if not isinstance(name, Filter):
                return name
            factory = name.factory()
        else:
            factory = self.__filters.get(name) or self.FILTERS.get(name)
            if not factory:
                return None

        try:
            if not isinstance(factory, collections.Callable):
                raise Error("invalid FILTER entry for '%s' (not callable)" %
                            (name, ))
            elif getattr(factory, "dynamic_filter", False):
                args = args or ()
                filter = factory(context, *args)
            else:
                filter = factory
            if not isinstance(filter, collections.Callable):
                raise Error("invalid FILTER for '%s' (not callable)" %
                            (name, ))
        except Exception as e:
            if self.__tolerant:
                return None
            if not isinstance(e, TemplateException):
                e = TemplateException(ERROR_FILTER, e)
            raise e

        return filter
Ejemplo n.º 13
0
 def throw(self, *args):
     raise TemplateException("date", ", ".join(str(x) for x in args))
Ejemplo n.º 14
0
 def throw(self, error):
     raise TemplateException("Image", error)
Ejemplo n.º 15
0
 def testException(self):
   text = "the current output buffer"
   e1 = TemplateException("e1.type", "e1.info")
   e2 = TemplateException("e2.type", "e2.info", StringBuffer(text))
   self.assertEquals("e1.type", e1.type())
   self.assertEquals("e2.info", e2.info())
   ti = e1.type_info()
   self.assertEquals("e1.type", ti[0])
   self.assertEquals("e1.info", ti[1])
   self.assertEquals("e2.type error - e2.info", str(e2))
   self.assertEquals("the current output buffer", e2.text())
   prepend = "text to prepend "
   e2.text(StringBuffer(prepend))
   self.assertEquals("text to prepend the current output buffer", e2.text())
   handlers = ("something", "e2", "e1.type")
   self.assertEquals("e1.type", e1.select_handler(handlers))
   self.assertEquals("e2", e2.select_handler(handlers))
   e3 = TemplateException("e3.type", "e3.info", None)
   self.assertEquals("", e3.text())
   self.assertEquals("e3.type error - e3.info", str(e3))
Ejemplo n.º 16
0
 def throw(self, error):
     """Throw a 'Directory' exception."""
     raise TemplateException("Directory", error)
Ejemplo n.º 17
0
 def testException(self):
     text = "the current output buffer"
     e1 = TemplateException("e1.type", "e1.info")
     e2 = TemplateException("e2.type", "e2.info", StringBuffer(text))
     self.assertEquals("e1.type", e1.type())
     self.assertEquals("e2.info", e2.info())
     ti = e1.type_info()
     self.assertEquals("e1.type", ti[0])
     self.assertEquals("e1.info", ti[1])
     self.assertEquals("e2.type error - e2.info", str(e2))
     self.assertEquals("the current output buffer", e2.text())
     prepend = "text to prepend "
     e2.text(StringBuffer(prepend))
     self.assertEquals("text to prepend the current output buffer",
                       e2.text())
     handlers = ("something", "e2", "e1.type")
     self.assertEquals("e1.type", e1.select_handler(handlers))
     self.assertEquals("e2", e2.select_handler(handlers))
     e3 = TemplateException("e3.type", "e3.info", None)
     self.assertEquals("", e3.text())
     self.assertEquals("e3.type error - e3.info", str(e3))
Ejemplo n.º 18
0
 def throw_egg(*_):
   raise TemplateException("egg", "scrambled")
Ejemplo n.º 19
0
 def throw(self, error):
     raise TemplateException('File', error)