Exemplo n.º 1
0
    def __call__(self, environ, start_response):
        rl = core.request_local()
        rl.clear()
        rl["middleware"] = self
        req = wo.Request(environ)

        path = req.path_info
        if self.config.serve_resources and path.startswith(self.config.res_prefix):
            return self.resources(environ, start_response)
        else:
            if self.config.serve_controllers and path.startswith(self.config.controller_prefix):
                resp = self.controllers(req)
            else:
                if self.app:
                    resp = req.get_response(self.app, catch_exc_info=True)
                else:
                    resp = wo.Response(status="404 Not Found")
            content_type = resp.headers.get("Content-Type", "text/plain").lower()
            if self.config.inject_resources and "html" in content_type:
                body = resources.inject_resources(resp.body, encoding=resp.charset)
                if isinstance(body, unicode):
                    resp.unicode_body = body
                else:
                    resp.body = body
        core.request_local().clear()
        return resp(environ, start_response)
Exemplo n.º 2
0
    def lookup_provided_translator(_sval):
        mw = core.request_local().get('middleware')
        if not mw:
            return _sval

        try:
            return core.request_local()['middleware'].config.translator(_sval)
        except TypeError:
            log.warn(traceback.format_exc())
            return _sval
Exemplo n.º 3
0
    def prepare(self):
        super(Resource, self).prepare()

        rl_resources = core.request_local().setdefault('resources', [])
        rl_location = core.request_local()['middleware'].config.inject_resources_location

        if self not in rl_resources:
            if self.location is '__use_middleware':
                self.location = rl_location
            for r in self.resources:
                r.req().prepare()

            rl_resources.append(self)
Exemplo n.º 4
0
def unflatten_params(params):
    """This performs the first stage of validation. It takes a dictionary where
    some keys will be compound names, such as "form:subform:field" and converts
    this into a nested dict/list structure. It also performs unicode decoding,
    with the encoding specified in the middleware config.
    """
    if isinstance(params, webob.MultiDict):
        params = params.mixed()
    mw = core.request_local().get('middleware')
    enc = mw.config.encoding if mw else 'utf-8'
    try:
        for p in params:
            if isinstance(params[p], str):
                params[p] = params[p].decode(enc)
    except UnicodeDecodeError:
        raise ValidationError('decode', Validator(encoding=enc))
    out = {}
    for pname in params:
        dct = out
        elements = pname.split(':')
        for e in elements[:-1]:
            dct = dct.setdefault(e, {})
        dct[elements[-1]] = params[pname]

    numdict_to_list(out)
    return out
Exemplo n.º 5
0
def unflatten_params(params):
    """This performs the first stage of validation. It takes a dictionary where
    some keys will be compound names, such as "form:subform:field" and converts
    this into a nested dict/list structure. It also performs unicode decoding,
    with the encoding specified in the middleware config.
    """
    if isinstance(params, webob.MultiDict):
        params = params.mixed()
    mw = core.request_local().get('middleware')
    enc = mw.config.encoding if mw else 'utf-8'
    try:
        for p in params:
            if isinstance(params[p], str):
                params[p] = params[p].decode(enc)
    except UnicodeDecodeError:
        raise ValidationError('decode', Validator(encoding=enc))
    out = {}
    for pname in params:
        dct = out
        elements = pname.split(':')
        for e in elements[:-1]:
            dct = dct.setdefault(e, {})
        dct[elements[-1]] = params[pname]

    numdict_to_list(out)
    return out
Exemplo n.º 6
0
def get_engine_name(template_name, mw=None):
    global engine_name_cache
    try:
        engine_name, template_path = template_name.split(':', 1)
        return engine_name
    except ValueError:
        pass
    try:
        return engine_name_cache[template_name]
    except KeyError:
        pass
    try:
        if mw is None:
            rl = core.request_local()
            mw = rl['middleware']
        pref_rend_eng = mw.config.preferred_rendering_engines
    except (KeyError, AttributeError):
        pref_rend_eng = ['mako', 'genshi', 'cheetah', 'kid']
    # find the first file in the preffered engines available for templating
    for engine_name in pref_rend_eng:
        if template_available(template_name, engine_name, mw):
            engine_name_cache[template_name] = engine_name
            return engine_name
    if not mw.config.strict_engine_selection:
        pref_rend_eng = ['mako', 'genshi', 'cheetah', 'kid']
        for engine_name in pref_rend_eng:
            if template_available(template_name, engine_name):
                engine_name_cache[template_name] = engine_name
                return engine_name
    raise EngineError(engine_error_template % (template_name, template_name))
Exemplo n.º 7
0
def get_rendering_extensions_lookup(mw):
    if mw is None:
        rl = core.request_local()
        mw = rl.get('middleware')
        if mw is None:
            return _default_rendering_extension_lookup
    return mw.config.rendering_extension_lookup
Exemplo n.º 8
0
def get_engine_name(template_name, mw=None):
    global engine_name_cache
    try:
        engine_name, template_path = template_name.split(':', 1)
        return engine_name
    except ValueError:
        pass
    try:
        return engine_name_cache[template_name]
    except KeyError:
        pass
    try:
        if mw is None:
            rl = core.request_local()
            mw = rl['middleware']
        pref_rend_eng = mw.config.preferred_rendering_engines
    except (KeyError, AttributeError):
        pref_rend_eng = ['mako', 'genshi', 'cheetah', 'kid']
    #find the first file in the preffered engines that is available for templating
    for engine_name in pref_rend_eng:
        if template_available(template_name, engine_name, mw):
            engine_name_cache[template_name] = engine_name
            return engine_name
    if not mw.config.strict_engine_selection:
        pref_rend_eng = ['mako', 'genshi', 'cheetah', 'kid']
        for engine_name in pref_rend_eng:
            if template_available(template_name, engine_name):
                engine_name_cache[template_name] = engine_name
                return engine_name
    raise EngineError("Could not find template for: %s. You may need to specify \
a template engine name in the widget like mako:%s, or change the middleware setup \
to include the template's templating language in your preferred_template_engines \
configuration. As a last resort, you may set strict_template_selection to false \
which will grab whatever template it finds if there one of your preferred template \
engines is not found."""%(template_name, template_name))
Exemplo n.º 9
0
    def load_engine(self, name, options={}, extra_vars_func=None):
        if name in self:
            raise EngineError("Template engine '%s' is already loaded" % name)
        # TODO -- produce a nicer message when dotted_template_lookup == None
        if name == 'mako':
            self[name] = dotted_template_lookup
            return self[name]

        orig_name = name
        if name == 'genshi_abs':
            name = 'genshi'
            options = dict(options)
            options.update({'genshi.search_path': '.'})

        try:
            mw = core.request_local()['middleware']
            factory = mw.config.available_rendering_engines[name]
        except (KeyError, AttributeError):
            mount_point = "python.templating.engines"
            for entrypoint in pk.iter_entry_points(mount_point):
                if entrypoint.name == name:
                    factory = entrypoint.load()
                    break
            else:
                raise EngineError("No template engine for '%s'" % name)

        self[orig_name] = factory(extra_vars_func, options)
Exemplo n.º 10
0
def register_resource(modname, filename, whole_dir):
    """ API function for registering resources *for serving*.

    This should not be confused with resource registration for *injection*.
    A resource must be registered for serving for it to be also registered for
    injection.

    If the middleware is available, the resource is directly registered with
    the ResourcesApp.

    If the middleware is not available, the resource is stored in the
    request_local dict.  When the middleware is later initialized, those
    waiting registrations are processed.
    """

    rl = core.request_local()
    mw = rl.get('middleware')
    if mw:
        mw.resources.register(modname, filename, whole_dir)
    else:
        rl['queued_resources'] = rl.get('queued_resources', []) + [
            (modname, filename, whole_dir)
        ]
        log.debug("No middleware in place.  Queued %r->%r(%r) registration." %
                  (modname, filename, whole_dir))
Exemplo n.º 11
0
def get_rendering_extensions_lookup(mw):
    if mw is None:
        rl = core.request_local()
        mw = rl.get('middleware')
        if mw is None:
            return _default_rendering_extension_lookup
    return mw.config.rendering_extension_lookup
Exemplo n.º 12
0
    def __call__(self, html, resources=None, encoding=None):
        """Injects resources, if any, into html string when called.

        .. note::
           Ignore the ``self`` parameter if seeing this as
           :func:`tw.core.resource_injector.inject_resources` docstring
           since it is an alias for an instance method of a private class.

        ``html`` must be a ``encoding`` encoded string. If ``encoding`` is not
        given it will be tried to be derived from a <meta>.

        """
        if resources is None:
            resources = core.request_local().get('resources', None)
        if resources:
            encoding = encoding or find_charset(html) or 'utf-8'
            html = util.MultipleReplacer.__call__(self, html, resources, encoding)
            core.request_local().pop('resources', None)
        return html
Exemplo n.º 13
0
    def prepare(self):
        super(ResourceBundle, self).prepare()

        rl = core.request_local()
        rl_resources = rl.setdefault('resources', [])
        rl_location = rl['middleware'].config.inject_resources_location

        if self not in rl_resources:
            for r in self.resources:
                r.req().prepare()
Exemplo n.º 14
0
    def prepare(self):
        super(ResourceBundle, self).prepare()

        rl = core.request_local()
        rl_resources = rl.setdefault('resources', [])
        rl_location = rl['middleware'].config.inject_resources_location

        if self not in rl_resources:
            for r in self.resources:
                r.req().prepare()
Exemplo n.º 15
0
    def __call__(self, html, resources=None, encoding=None):
        """Injects resources, if any, into html string when called.

        .. note::
           Ignore the ``self`` parameter if seeing this as
           :func:`tw.core.resource_injector.inject_resources` docstring
           since it is an alias for an instance method of a private class.

        ``html`` must be a ``encoding`` encoded string. If ``encoding`` is not
        given it will be tried to be derived from a <meta>.

        """
        if resources is None:
            resources = core.request_local().get('resources', None)
        if resources:
            encoding = encoding or find_charset(html) or 'utf-8'
            html = util.MultipleReplacer.__call__(self, html, resources,
                                                  encoding)
            core.request_local().pop('resources', None)
        return html
Exemplo n.º 16
0
 def prepare(self):
     rl = core.request_local()
     if not self.no_inject:
         if not hasattr(self, 'link'):
             # TBD shouldn't we test for this in __new__ ?
             if not self.filename:
                 raise pm.ParameterError(
                     "Either 'link' or 'filename' must be specified")
             resources = rl['middleware'].resources
             self.link = resources.resource_path(self.modname or '__anon__',
                                                 self.filename)
         super(Link, self).prepare()
Exemplo n.º 17
0
    def __init__(self, app, controllers=None, **config):
        self.app = app
        self.config = Config(**config)
        self.engines = template.EngineManager()
        self.resources = resources.ResourcesApp(self.config)
        self.controllers = controllers or ControllersApp()

        rl = core.request_local()
        for widget, path in rl.get("queued_controllers", []):
            self.controllers.register(widget, path)

        rl["queued_controllers"] = []
Exemplo n.º 18
0
    def prepare(self):
        super(Resource, self).prepare()

        rl = core.request_local()
        rl_resources = rl.setdefault('resources', [])
        rl_location = rl['middleware'].config.inject_resources_location

        if self not in rl_resources:
            if self.location is '__use_middleware':
                self.location = rl_location

            rl_resources.append(self)
Exemplo n.º 19
0
 def __init__(self, msg, validator=None, widget=None):
     self.widget = widget
     validator = validator or Validator
     mw = core.request_local().get('middleware')
     if isinstance(validator, Validator):
         msg = validator.msg_rewrites.get(msg, msg)
     if mw and msg in mw.config.validator_msgs:
         msg = mw.config.validator_msgs[msg]
     elif hasattr(validator, 'msgs') and msg in validator.msgs:
         msg = validator.msgs.get(msg, msg)
     msg = re.sub('\$(\w+)',
             lambda m: str(getattr(validator, m.group(1))), unicode(msg))
     super(ValidationError, self).__init__(msg)
Exemplo n.º 20
0
    def __call__(self, environ, start_response):
        rl = core.request_local()
        rl.clear()
        rl['middleware'] = self
        req = wo.Request(environ)

        path = req.path_info
        if self.config.serve_resources and \
           path.startswith(self.config.res_prefix):
            return self.resources(environ, start_response)
        else:
            if self.config.serve_controllers and \
               path.startswith(self.config.controller_prefix):
                resp = self.controllers(req)
            else:
                if self.app:
                    resp = req.get_response(self.app, catch_exc_info=True)
                else:
                    resp = wo.Response(status="404 Not Found")

            ct = resp.headers.get('Content-Type', 'text/plain').lower()

            should_inject = (
                self.config.inject_resources
                and 'html' in ct
                and not isinstance(resp.app_iter, types.GeneratorType)
            )
            if should_inject:
                body = resources.inject_resources(
                    resp.body,
                    encoding=resp.charset,
                )
                if isinstance(body, unicode):
                    resp.unicode_body = body
                else:
                    resp.body = body
        core.request_local().clear()
        return resp(environ, start_response)
Exemplo n.º 21
0
 def prepare(self):
     rl = core.request_local()
     if not self.no_inject:
         if not hasattr(self, 'link'):
             # TBD shouldn't we test for this in __new__ ?
             if not self.filename:
                 raise pm.ParameterError(
                     "Either 'link' or 'filename' must be specified"
                 )
             resources = rl['middleware'].resources
             self.link = resources.resource_path(
                 self.modname or '__anon__', self.filename
             )
         super(Link, self).prepare()
Exemplo n.º 22
0
    def lookup_provided_translator(_sval):
        mw = core.request_local().get('middleware')
        if not mw:
            return _sval

        try:
            translator = get_translator(mw.config.get_lang())
        except AttributeError:
            try:
                translator = mw.config.translator
            except AttributeError:
                return _sval

        return translator(_sval)
Exemplo n.º 23
0
    def __call__(self, environ, start_response):
        rl = core.request_local()
        rl.clear()
        rl['middleware'] = self
        req = wo.Request(environ)

        path = req.path_info
        if self.config.serve_resources and \
           path.startswith(self.config.res_prefix):
            return self.resources(environ, start_response)
        else:
            if self.config.serve_controllers and \
               path.startswith(self.config.controller_prefix):
                resp = self.controllers(req)
            else:
                if self.app:
                    resp = req.get_response(self.app, catch_exc_info=True)
                else:
                    resp = wo.Response(status="404 Not Found")

            ct = resp.headers.get('Content-Type', 'text/plain').lower()

            should_inject = (
                self.config.inject_resources and 'html' in ct
                and not isinstance(resp.app_iter, types.GeneratorType))
            if should_inject:
                body = resources.inject_resources(
                    resp.body,
                    encoding=resp.charset,
                )
                if isinstance(body, unicode):
                    resp.unicode_body = body
                else:
                    resp.body = body
        core.request_local().clear()
        return resp(environ, start_response)
Exemplo n.º 24
0
 def __call__(self, req):
     config = rl = core.request_local()['middleware'].config
     path = req.path_info.split('/')[1:]
     pre = config.controller_prefix.strip('/')
     if pre and path[0] != pre:
         return wo.Response(status="404 Not Found")
     path = path[1] if pre else path[0]
     widget_name = path or 'index'
     try:
         widget = self._widgets[widget_name]
     except KeyError:
         resp = wo.Response(status="404 Not Found")
     else:
         resp = widget.request(req)
     return resp
Exemplo n.º 25
0
 def __call__(self, req):
     config = rl = core.request_local()["middleware"].config
     path = req.path_info.split("/")[1:]
     pre = config.controller_prefix.strip("/")
     if pre and path[0] != pre:
         return wo.Response(status="404 Not Found")
     path = path[1] if pre else path[0]
     widget_name = path or "index"
     try:
         widget = self._widgets[widget_name]
     except KeyError:
         resp = wo.Response(status="404 Not Found")
     else:
         resp = widget.request(req)
     return resp
Exemplo n.º 26
0
    def __init__(self, app, controllers=None, **config):
        self.app = app
        self.config = Config(**config)
        self.resources = resources.ResourcesApp(self.config)
        self.controllers = controllers or ControllersApp()

        rl = core.request_local()
        # Load up controllers that wanted to be registered before we were ready
        for widget, path in rl.get('queued_controllers', []):
            self.controllers.register(widget, path)

        rl['queued_controllers'] = []

        # Load up resources that wanted to be registered before we were ready
        for modname, filename, whole_dir in rl.get('queued_resources', []):
            self.resources.register(modname, filename, whole_dir)

        rl['queued_resources'] = []
Exemplo n.º 27
0
    def __init__(self, app, controllers=None, **config):
        self.app = app
        self.config = Config(**config)
        self.resources = resources.ResourcesApp(self.config)
        self.controllers = controllers or ControllersApp()

        rl = core.request_local()
        # Load up controllers that wanted to be registered before we were ready
        for widget, path in rl.get("queued_controllers", []):
            self.controllers.register(widget, path)

        rl["queued_controllers"] = []

        # Load up resources that wanted to be registered before we were ready
        for modname, filename, whole_dir in rl.get("queued_resources", []):
            self.resources.register(modname, filename, whole_dir)

        rl["queued_resources"] = []
Exemplo n.º 28
0
def register_controller(widget, path):
    """ API function for registering widget controllers.

    If the middleware is available, the widget is directly registered with the
    ControllersApp.

    If the middleware is not available, the widget is stored in the
    request_local dict.  When the middleware is later initialized, those
    waiting registrations are processed.
    """

    rl = core.request_local()
    mw = rl.get("middleware")
    if mw:
        mw.controllers.register(widget, path)
    else:
        rl["queued_controllers"] = rl.get("queued_controllers", []) + [(widget, path)]
        log.info("No middleware in place.  Queued %r->%r registration." % (path, widget))
Exemplo n.º 29
0
    def __init__(self, app, controllers=None, **config):
        self.app = app
        self.config = Config(**config)
        self.engines = template.EngineManager()
        self.resources = resources.ResourcesApp(self.config)
        self.controllers = controllers or ControllersApp()

        rl = core.request_local()
        # Load up controllers that wanted to be registered before we were ready
        for widget, path in rl.get('queued_controllers', []):
            self.controllers.register(widget, path)

        rl['queued_controllers'] = []

        # Load up resources that wanted to be registered before we were ready
        for modname, filename in rl.get('queued_resources', []):
            self.resources.register(modname, filename)

        rl['queued_resources'] = []
Exemplo n.º 30
0
    def __init__(self, msg, validator=None, widget=None):
        self.widget = widget
        validator = validator or Validator
        mw = core.request_local().get('middleware')
        if isinstance(validator, Validator):
            msg = validator.msg_rewrites.get(msg, msg)

        if mw and msg in mw.config.validator_msgs:
            msg = mw.config.validator_msgs[msg]
        elif hasattr(validator, 'msgs') and msg in validator.msgs:
            msg = validator.msgs.get(msg, msg)

        # In the event that the user specified a form-wide validator but
        # they did not specify a childerror message, show no error.
        if msg == 'childerror':
            msg = ''

        msg = re.sub('\$(\w+)',
                lambda m: str(getattr(validator, m.group(1))), unicode(msg))
        super(ValidationError, self).__init__(msg)
Exemplo n.º 31
0
def register_controller(widget, path):
    """ API function for registering widget controllers.

    If the middleware is available, the widget is directly registered with the
    ControllersApp.

    If the middleware is not available, the widget is stored in the
    request_local dict.  When the middleware is later initialized, those
    waiting registrations are processed.
    """

    rl = core.request_local()
    mw = rl.get('middleware')
    if mw:
        mw.controllers.register(widget, path)
    else:
        rl['queued_controllers'] = \
                rl.get('queued_controllers', []) + [(widget, path)]
        log.debug("No middleware in place.  Queued %r->%r registration." %
                  (path, widget))
Exemplo n.º 32
0
    def __init__(self, msg, validator=None, widget=None):
        self.widget = widget
        validator = validator or Validator
        mw = core.request_local().get('middleware')
        if isinstance(validator, Validator):
            msg = validator.msg_rewrites.get(msg, msg)

        if mw and msg in mw.config.validator_msgs:
            msg = mw.config.validator_msgs[msg]
        elif hasattr(validator, 'msgs') and msg in validator.msgs:
            msg = validator.msgs.get(msg, msg)

        # In the event that the user specified a form-wide validator but
        # they did not specify a childerror message, show no error.
        if msg == 'childerror':
            msg = ''

        msg = re.sub('\$(\w+)',
                lambda m: str(getattr(validator, m.group(1))), unicode(msg))
        super(ValidationError, self).__init__(msg)
Exemplo n.º 33
0
    def get_template(self, template_name):
        """this is the emulated method that must return a template
        instance based on a given template name
        """

        if not self.template_cache.has_key(template_name):
            # the template string is not yet loaded into the cache.
            # Do so now
            self.__load(template_name)

        try:
            # AUTO RELOADING will be activated only if user has
            # explicitly asked for it in the configuration
            # return the template, but first make sure it's not outdated
            # and if outdated, refresh the cache.
            if getattr(core.request_local()['middleware'].config, 'auto_reload_templates', False):
                return self.__check(self.template_cache[template_name])
        except (AttributeError, KeyError):
            pass

        return self.template_cache[template_name]
Exemplo n.º 34
0
    def __init__(self, app, controllers=None, **config):
        self.app = app
        self.config = Config(**config)
        self.resources = resources.ResourcesApp(self.config)
        self.controllers = controllers or ControllersApp()

        rl = core.request_local()
        # Load up controllers that wanted to be registered before we were ready
        for widget, path in rl.get('queued_controllers', []):
            self.controllers.register(widget, path)

        rl['queued_controllers'] = []

        # Load up resources that wanted to be registered before we were ready
        for modname, filename, whole_dir in rl.get('queued_resources', []):
            self.resources.register(modname, filename, whole_dir)

        rl['queued_resources'] = []

        # Future resource registrations should know to just plug themselves into
        # me right away (instead of being queued).
        rl['middleware'] = self
Exemplo n.º 35
0
    def __init__(self, app, controllers=None, **config):
        self.app = app
        self.config = Config(**config)
        self.resources = resources.ResourcesApp(self.config)
        self.controllers = controllers or ControllersApp()

        rl = core.request_local()
        # Load up controllers that wanted to be registered before we were ready
        for widget, path in rl.get('queued_controllers', []):
            self.controllers.register(widget, path)

        rl['queued_controllers'] = []

        # Load up resources that wanted to be registered before we were ready
        for modname, filename, whole_dir in rl.get('queued_resources', []):
            self.resources.register(modname, filename, whole_dir)

        rl['queued_resources'] = []

        # Future resource registrations should know to just plug themselves into
        # me right away (instead of being queued).
        rl['middleware'] = self
Exemplo n.º 36
0
def get_engine_name(template_name, mw=None):
    global engine_name_cache

    if template_name in engine_name_cache:
        return engine_name_cache[template_name]

    if ':' in template_name:
        engine_name = template_name.split(':', 1)[0]
        engine_name_cache[template_name] = engine_name
        return engine_name

    try:
        if mw is None:
            rl = core.request_local()
            mw = rl['middleware']
        pref_rend_eng = mw.config.preferred_rendering_engines
    except (KeyError, AttributeError):
        pref_rend_eng = ['mako', 'genshi', 'jinja', 'kajiki', 'chameleon']

    # find the first file in the preffered engines available for templating
    for engine_name in pref_rend_eng:
        try:
            get_source(engine_name, template_name, mw=mw)
            engine_name_cache[template_name] = engine_name
            return engine_name
        except IOError:
            pass

    if not mw.config.strict_engine_selection:
        pref_rend_eng = ['mako', 'genshi', 'jinja', 'kajiki', 'chameleon']
        for engine_name in pref_rend_eng:
            try:
                get_source(engine_name, template_name, mw=mw)
                engine_name_cache[template_name] = engine_name
                return engine_name
            except IOError:
                pass

    raise ValueError("Could not find engine name for %s" % template_name)
Exemplo n.º 37
0
def get_engine_name(template_name, mw=None):
    if template_name in engine_name_cache:
        return engine_name_cache[template_name]

    if ':' in template_name:
        engine_name = template_name.split(':', 1)[0]
        engine_name_cache[template_name] = engine_name
        return engine_name

    try:
        if mw is None:
            rl = core.request_local()
            mw = rl['middleware']
        pref_rend_eng = mw.config.preferred_rendering_engines
    except (KeyError, AttributeError):
        pref_rend_eng = ['mako', 'genshi', 'jinja', 'kajiki', 'chameleon']

    # find the first file in the preffered engines available for templating
    for engine_name in pref_rend_eng:
        try:
            get_source(engine_name, template_name, mw=mw)
            engine_name_cache[template_name] = engine_name
            return engine_name
        except IOError:
            pass

    if not mw.config.strict_engine_selection:
        pref_rend_eng = ['mako', 'genshi', 'jinja', 'kajiki', 'chameleon']
        for engine_name in pref_rend_eng:
            try:
                get_source(engine_name, template_name, mw=mw)
                engine_name_cache[template_name] = engine_name
                return engine_name
            except IOError:
                pass

    raise ValueError("Could not find engine name for %s" % template_name)
Exemplo n.º 38
0
def register_resource(modname, filename, whole_dir):
    """ API function for registering resources *for serving*.

    This should not be confused with resource registration for *injection*.
    A resource must be registered for serving for it to be also registered for
    injection.

    If the middleware is available, the resource is directly registered with
    the ResourcesApp.

    If the middleware is not available, the resource is stored in the
    request_local dict.  When the middleware is later initialized, those
    waiting registrations are processed.
    """

    rl = core.request_local()
    mw = rl.get('middleware')
    if mw:
        mw.resources.register(modname, filename, whole_dir)
    else:
        rl['queued_resources'] = rl.get('queued_resources',
                                        []) + [(modname, filename, whole_dir)]
        log.debug("No middleware in place.  Queued %r->%r(%r) registration." %
                  (modname, filename, whole_dir))
Exemplo n.º 39
0
 def prepare(self):
     resources = core.request_local()['middleware'].resources
     self.link = resources.resource_path(
         self.modname,
         self.filename,
     )
Exemplo n.º 40
0
 def prepare(self):
     resources = core.request_local()['middleware'].resources
     self.link = resources.register(self.modname, self.filename, whole_dir=True)
Exemplo n.º 41
0
 def lookup_provided_translator(_sval):
     mw = core.request_local().get('middleware')
     if not mw:
         return _sval
     return core.request_local()['middleware'].config.translator(_sval)
Exemplo n.º 42
0
 def prepare(self):
     resources = core.request_local()['middleware'].resources
     self.link = resources.resource_path(
         self.modname,
         self.filename,
     )