示例#1
0
    def generator(dict):
        newdict = {}
        for k, v in dict.items():
            if PY3: # pragma: no cover
                if v.__class__ is binary_type:
                    # url_quote below needs a native string, not bytes on Py3
                    v = v.decode('utf-8')
            else:
                if v.__class__ is text_type:
                    # url_quote below needs bytes, not unicode on Py2
                    v = v.encode('utf-8')

            if k == remainder:
                # a stararg argument
                if is_nonstr_iter(v):
                    v = '/'.join([quote_path_segment(x) for x in v]) # native
                else:
                    if v.__class__ not in string_types:
                        v = str(v)
                    v = quote_path_segment(v, safe='/')
            else:
                if v.__class__ not in string_types:
                    v = str(v)
                    # v may be bytes (py2) or native string (py3)
                v = quote_path_segment(v)

            # at this point, the value will be a native string
            newdict[k] = v

        result = gen % newdict # native string result
        return result
示例#2
0
    def __call__(self, request):
        environ = request.environ
        matchdict = request.matchdict

        if matchdict is not None:
            path = matchdict.get('traverse', slash) or slash
            if is_nonstr_iter(path):
                # this is a *traverse stararg (not a {traverse})
                # routing has already decoded these elements, so we just
                # need to join them
                path = slash.join(path) or slash

            subpath = matchdict.get('subpath', ())
            if not is_nonstr_iter(subpath):
                # this is not a *subpath stararg (just a {subpath})
                # routing has already decoded this string, so we just need
                # to split it
                subpath = split_path_info(subpath)

        else:
            # this request did not match a route
            subpath = ()
            try:
                # empty if mounted under a path in mod_wsgi, for example
                path = request.path_info or slash
            except KeyError:
                # if environ['PATH_INFO'] is just not there
                path = slash
            except UnicodeDecodeError as e:
                raise URLDecodeError(e.encoding, e.object, e.start, e.end,
                                     e.reason)

        if VH_ROOT_KEY in environ:
            # HTTP_X_VHM_ROOT
            vroot_path = decode_path_info(environ[VH_ROOT_KEY])
            vroot_tuple = split_path_info(vroot_path)
            vpath = vroot_path + path # both will (must) be unicode or asciistr
            vroot_idx = len(vroot_tuple) - 1
        else:
            vroot_tuple = ()
            vpath = path
            vroot_idx = -1

        root = self.root
        ob = vroot = root

        if vpath == slash: # invariant: vpath must not be empty
            # prevent a call to traversal_path if we know it's going
            # to return the empty tuple
            vpath_tuple = ()
        else:
            # we do dead reckoning here via tuple slicing instead of
            # pushing and popping temporary lists for speed purposes
            # and this hurts readability; apologies
            i = 0
            view_selector = self.VIEW_SELECTOR
            vpath_tuple = split_path_info(vpath)
            for segment in vpath_tuple:
                if segment[:2] == view_selector:
                    return {'context': ob,
                            'view_name': segment[2:],
                            'subpath': vpath_tuple[i + 1:],
                            'traversed': vpath_tuple[:vroot_idx + i + 1],
                            'virtual_root': vroot,
                            'virtual_root_path': vroot_tuple,
                            'root': root}
                try:
                    getitem = ob.__getitem__
                except AttributeError:
                    return {'context': ob,
                            'view_name': segment,
                            'subpath': vpath_tuple[i + 1:],
                            'traversed': vpath_tuple[:vroot_idx + i + 1],
                            'virtual_root': vroot,
                            'virtual_root_path': vroot_tuple,
                            'root': root}

                try:
                    next = getitem(segment)
                except KeyError:
                    return {'context': ob,
                            'view_name': segment,
                            'subpath': vpath_tuple[i + 1:],
                            'traversed': vpath_tuple[:vroot_idx + i + 1],
                            'virtual_root': vroot,
                            'virtual_root_path': vroot_tuple,
                            'root': root}
                if i == vroot_idx:
                    vroot = next
                ob = next
                i += 1

        return {'context': ob, 'view_name': empty, 'subpath': subpath,
                'traversed': vpath_tuple, 'virtual_root': vroot,
                'virtual_root_path': vroot_tuple, 'root': root}
示例#3
0
def traverse(resource, path):
    """Given a resource object as ``resource`` and a string or tuple
    representing a path as ``path`` (such as the return value of
    :func:`pyramid.traversal.resource_path` or
    :func:`pyramid.traversal.resource_path_tuple` or the value of
    ``request.environ['PATH_INFO']``), return a dictionary with the
    keys ``context``, ``root``, ``view_name``, ``subpath``,
    ``traversed``, ``virtual_root``, and ``virtual_root_path``.

    A definition of each value in the returned dictionary:

    - ``context``: The :term:`context` (a :term:`resource` object) found
      via traversal or url dispatch.  If the ``path`` passed in is the
      empty string, the value of the ``resource`` argument passed to this
      function is returned.

    - ``root``: The resource object at which :term:`traversal` begins.
      If the ``resource`` passed in was found via url dispatch or if the
      ``path`` passed in was relative (non-absolute), the value of the
      ``resource`` argument passed to this function is returned.

    - ``view_name``: The :term:`view name` found during
      :term:`traversal` or :term:`url dispatch`; if the ``resource`` was
      found via traversal, this is usually a representation of the
      path segment which directly follows the path to the ``context``
      in the ``path``.  The ``view_name`` will be a Unicode object or
      the empty string.  The ``view_name`` will be the empty string if
      there is no element which follows the ``context`` path.  An
      example: if the path passed is ``/foo/bar``, and a resource
      object is found at ``/foo`` (but not at ``/foo/bar``), the 'view
      name' will be ``u'bar'``.  If the ``resource`` was found via
      urldispatch, the view_name will be the name the route found was
      registered with.

    - ``subpath``: For a ``resource`` found via :term:`traversal`, this
      is a sequence of path segments found in the ``path`` that follow
      the ``view_name`` (if any).  Each of these items is a Unicode
      object.  If no path segments follow the ``view_name``, the
      subpath will be the empty sequence.  An example: if the path
      passed is ``/foo/bar/baz/buz``, and a resource object is found at
      ``/foo`` (but not ``/foo/bar``), the 'view name' will be
      ``u'bar'`` and the :term:`subpath` will be ``[u'baz', u'buz']``.
      For a ``resource`` found via url dispatch, the subpath will be a
      sequence of values discerned from ``*subpath`` in the route
      pattern matched or the empty sequence.

    - ``traversed``: The sequence of path elements traversed from the
      root to find the ``context`` object during :term:`traversal`.
      Each of these items is a Unicode object.  If no path segments
      were traversed to find the ``context`` object (e.g. if the
      ``path`` provided is the empty string), the ``traversed`` value
      will be the empty sequence.  If the ``resource`` is a resource found
      via :term:`url dispatch`, traversed will be None.

    - ``virtual_root``: A resource object representing the 'virtual' root
      of the resource tree being traversed during :term:`traversal`.
      See :ref:`vhosting_chapter` for a definition of the virtual root
      object.  If no virtual hosting is in effect, and the ``path``
      passed in was absolute, the ``virtual_root`` will be the
      *physical* root resource object (the object at which :term:`traversal`
      begins).  If the ``resource`` passed in was found via :term:`URL
      dispatch` or if the ``path`` passed in was relative, the
      ``virtual_root`` will always equal the ``root`` object (the
      resource passed in).

    - ``virtual_root_path`` -- If :term:`traversal` was used to find
      the ``resource``, this will be the sequence of path elements
      traversed to find the ``virtual_root`` resource.  Each of these
      items is a Unicode object.  If no path segments were traversed
      to find the ``virtual_root`` resource (e.g. if virtual hosting is
      not in effect), the ``traversed`` value will be the empty list.
      If url dispatch was used to find the ``resource``, this will be
      ``None``.

    If the path cannot be resolved, a :exc:`KeyError` will be raised.

    Rules for passing a *string* as the ``path`` argument: if the
    first character in the path string is the with the ``/``
    character, the path will considered absolute and the resource tree
    traversal will start at the root resource.  If the first character
    of the path string is *not* the ``/`` character, the path is
    considered relative and resource tree traversal will begin at the resource
    object supplied to the function as the ``resource`` argument.  If an
    empty string is passed as ``path``, the ``resource`` passed in will
    be returned.  Resource path strings must be escaped in the following
    manner: each Unicode path segment must be encoded as UTF-8 and
    each path segment must escaped via Python's :mod:`urllib.quote`.
    For example, ``/path/to%20the/La%20Pe%C3%B1a`` (absolute) or
    ``to%20the/La%20Pe%C3%B1a`` (relative).  The
    :func:`pyramid.traversal.resource_path` function generates strings
    which follow these rules (albeit only absolute ones).

    Rules for passing a *tuple* as the ``path`` argument: if the first
    element in the path tuple is the empty string (for example ``('',
    'a', 'b', 'c')``, the path is considered absolute and the resource tree
    traversal will start at the resource tree root object.  If the first
    element in the path tuple is not the empty string (for example
    ``('a', 'b', 'c')``), the path is considered relative and resource tree
    traversal will begin at the resource object supplied to the function
    as the ``resource`` argument.  If an empty sequence is passed as
    ``path``, the ``resource`` passed in itself will be returned.  No
    URL-quoting or UTF-8-encoding of individual path segments within
    the tuple is required (each segment may be any string or unicode
    object representing a resource name).

    Explanation of the conversion of ``path`` segment values to
    Unicode during traversal: Each segment is URL-unquoted, and
    decoded into Unicode. Each segment is assumed to be encoded using
    the UTF-8 encoding (or a subset, such as ASCII); a
    :exc:`pyramid.exceptions.URLDecodeError` is raised if a segment
    cannot be decoded.  If a segment name is empty or if it is ``.``,
    it is ignored.  If a segment name is ``..``, the previous segment
    is deleted, and the ``..`` is ignored.  As a result of this
    process, the return values ``view_name``, each element in the
    ``subpath``, each element in ``traversed``, and each element in
    the ``virtual_root_path`` will be Unicode as opposed to a string,
    and will be URL-decoded.
    """

    if is_nonstr_iter(path):
        # the traverser factory expects PATH_INFO to be a string, not
        # unicode and it expects path segments to be utf-8 and
        # urlencoded (it's the same traverser which accepts PATH_INFO
        # from user agents; user agents always send strings).
        if path:
            path = _join_path_tuple(tuple(path))
        else:
            path = ''

    # The user is supposed to pass us a string object, never Unicode.  In
    # practice, however, users indeed pass Unicode to this API.  If they do
    # pass a Unicode object, its data *must* be entirely encodeable to ASCII,
    # so we encode it here as a convenience to the user and to prevent
    # second-order failures from cropping up (all failures will occur at this
    # step rather than later down the line as the result of calling
    # ``traversal_path``).

    path = ascii_native_(path)

    if path and path[0] == '/':
        resource = find_root(resource)

    reg = get_current_registry()

    request_factory = reg.queryUtility(IRequestFactory)
    if request_factory is None:
        from pyramid.request import Request # avoid circdep

        request_factory = Request

    request = request_factory.blank(path)
    request.registry = reg
    traverser = reg.queryAdapter(resource, ITraverser)
    if traverser is None:
        traverser = ResourceTreeTraverser(resource)

    return traverser(request)
    def __call__(self, info):
        p = re.compile(r"(?P<asset>[\w_.:/-]+)" r"(?:\#(?P<defname>[\w_]+))?" r"(\.(?P<ext>.*))")
        asset, defname, ext = p.match(info.name).group("asset", "defname", "ext")
        path = "%s.%s" % (asset, ext)
        registry = info.registry
        settings = info.settings
        settings_prefix = self.settings_prefix

        if settings_prefix is None:
            settings_prefix = info.type + "."

        lookup = registry.queryUtility(IMakoLookup, name=settings_prefix)

        def sget(name, default=None):
            return settings.get(settings_prefix + name, default)

        if lookup is None:
            reload_templates = settings.get("pyramid.reload_templates", None)
            if reload_templates is None:
                reload_templates = settings.get("reload_templates", False)
            reload_templates = asbool(reload_templates)
            directories = sget("directories", [])
            module_directory = sget("module_directory", None)
            input_encoding = sget("input_encoding", "utf-8")
            error_handler = sget("error_handler", None)
            default_filters = sget("default_filters", "h")
            imports = sget("imports", None)
            strict_undefined = asbool(sget("strict_undefined", False))
            preprocessor = sget("preprocessor", None)
            if not is_nonstr_iter(directories):
                directories = list(filter(None, directories.splitlines()))
            directories = [abspath_from_asset_spec(d) for d in directories]
            if module_directory is not None:
                module_directory = abspath_from_asset_spec(module_directory)
            if error_handler is not None:
                dotted = DottedNameResolver(info.package)
                error_handler = dotted.maybe_resolve(error_handler)
            if default_filters is not None:
                if not is_nonstr_iter(default_filters):
                    default_filters = list(filter(None, default_filters.splitlines()))
            if imports is not None:
                if not is_nonstr_iter(imports):
                    imports = list(filter(None, imports.splitlines()))
            if preprocessor is not None:
                dotted = DottedNameResolver(info.package)
                preprocessor = dotted.maybe_resolve(preprocessor)

            lookup = PkgResourceTemplateLookup(
                directories=directories,
                module_directory=module_directory,
                input_encoding=input_encoding,
                error_handler=error_handler,
                default_filters=default_filters,
                imports=imports,
                filesystem_checks=reload_templates,
                strict_undefined=strict_undefined,
                preprocessor=preprocessor,
            )

            with registry_lock:
                registry.registerUtility(lookup, IMakoLookup, name=settings_prefix)

        return MakoLookupTemplateRenderer(path, defname, lookup)