Exemplo n.º 1
0
def relative_url_for(endpoint, **values):
    """
    Like :func:`~flask.url_for`, but returns relative URLs if possible.

    Absolute URLs (with ``_external=True`` or to a different subdomain) are
    unchanged, but eg. ``/foo/bar`` becomes ``../bar``, depending on the
    current request context's path. (This, of course, requires a Flask
    :ref:`request context <flask:request-context>`.)

    URLs that would otherwise end with ``/`` get ``index.html`` appended,
    as Frozen-Flask does in filenames. Because of this behavior, this function
    should only be used with Frozen-Flask, not when running the application in
    :meth:`app.run() <flask.Flask.run>` or another WSGI sever.

    If the ``FREEZER_RELATIVE_URLS`` `configuration`_ is True, Frozen-Flask
    will automatically patch the application's Jinja environment so that
    ``url_for`` in templates is this function.
    """
    url = url_for(endpoint, **values)

    # absolute URLs in http://... (with subdomains or _external=True)
    if not url.startswith('/'):
        return url

    url, fragment_sep, fragment = url.partition('#')
    url, query_sep, query = url.partition('?')
    if url.endswith('/'):
        url += 'index.html'
    url += query_sep + query + fragment_sep + fragment

    request_path = request.path
    if not request_path.endswith('/'):
        request_path = posixpath.dirname(request_path)

    return posix_relpath(url, request_path)
Exemplo n.º 2
0
def relative_url_for(endpoint, **values):
    """
    Like :func:`~flask.url_for`, but returns relative URLs if possible.

    Absolute URLs (with ``_external=True`` or to a different subdomain) are
    unchanged, but eg. ``/foo/bar`` becomes ``../bar``, depending on the
    current request context's path. (This, of course, requires a Flask
    :ref:`request context <flask:request-context>`.)

    URLs that would otherwise end with ``/`` get ``index.html`` appended,
    as Frozen-Flask does in filenames. Because of this behavior, this function
    should only be used with Frozen-Flask, not when running the application in
    :meth:`app.run() <flask.Flask.run>` or another WSGI sever.

    If the ``FREEZER_RELATIVE_URLS`` `configuration`_ is True, Frozen-Flask
    will automatically patch the application's Jinja environment so that
    ``url_for`` in templates is this function.
    """
    url = url_for(endpoint, **values)

    # absolute URLs in http://... (with subdomains or _external=True)
    if not url.startswith('/'):
        return url

    url, fragment_sep, fragment = url.partition('#')
    url, query_sep, query = url.partition('?')
    if url.endswith('/'):
        url += 'index.html'
    url += query_sep + query + fragment_sep + fragment

    request_path = request.path
    if not request_path.endswith('/'):
        request_path = posixpath.dirname(request_path)

    return posix_relpath(url, request_path)