Ejemplo n.º 1
0
 def build_absolute_uri(self, location=None):
     """
     Build an absolute URI from the location and the variables available in
     this request. If no ``location`` is specified, build the absolute URI
     using request.get_full_path(). If the location is absolute, convert it
     to an RFC 3987 compliant URI and return it. If location is relative or
     is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base
     URL constructed from the request variables.
     """
     if location is None:
         # Make it an absolute url (but schemeless and domainless) for the
         # edge case that the path starts with '//'.
         location = '//%s' % self.get_full_path()
     bits = urlsplit(location)
     if not (bits.scheme and bits.netloc):
         # Handle the simple, most common case. If the location is absolute
         # and a scheme or host (netloc) isn't provided, skip an expensive
         # urljoin() as long as no path segments are '.' or '..'.
         if (bits.path.startswith('/') and not bits.scheme and not bits.netloc and
                 '/./' not in bits.path and '/../' not in bits.path):
             # If location starts with '//' but has no netloc, reuse the
             # schema and netloc from the current request. Strip the double
             # slashes and continue as if it wasn't specified.
             if location.startswith('//'):
                 location = location[2:]
             location = self._current_scheme_host + location
         else:
             # Join the constructed URL with the provided location, which
             # allows the provided location to apply query strings to the
             # base path.
             location = urljoin(self._current_scheme_host + self.path, location)
     return iri_to_uri(location)
Ejemplo n.º 2
0
 def __init__(self, redirect_to, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self['Location'] = iri_to_uri(redirect_to)
     parsed = urlparse(str(redirect_to))
     if parsed.scheme and parsed.scheme not in self.allowed_schemes:
         raise DisallowedRedirect(
             "Unsafe redirect to URL with protocol '%s'" % parsed.scheme)
Ejemplo n.º 3
0
 def handle_simple(cls, name):
     try:
         from server.conf import settings
     except ImportError:
         prefix = ''
     else:
         prefix = iri_to_uri(getattr(settings, name, ''))
     return prefix
Ejemplo n.º 4
0
def add_domain(domain, url, secure=False):
    protocol = 'https' if secure else 'http'
    if url.startswith('//'):
        # Support network-path reference (see #16753) - RSS requires a protocol
        url = '%s:%s' % (protocol, url)
    elif not url.startswith(('http://', 'https://', 'mailto:')):
        url = iri_to_uri('%s://%s%s' % (protocol, domain, url))
    return url
Ejemplo n.º 5
0
 def _get_full_path(self, path, force_append_slash):
     # RFC 3986 requires query string arguments to be in the ASCII range.
     # Rather than crash if this doesn't happen, we encode defensively.
     return '%s%s%s' % (
         escape_uri_path(path),
         '/' if force_append_slash and not path.endswith('/') else '',
         ('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) if self.META.get('QUERY_STRING', '') else ''
     )
Ejemplo n.º 6
0
    def add_item(self,
                 title,
                 link,
                 description,
                 author_email=None,
                 author_name=None,
                 author_link=None,
                 pubdate=None,
                 comments=None,
                 unique_id=None,
                 unique_id_is_permalink=None,
                 categories=(),
                 item_copyright=None,
                 ttl=None,
                 updateddate=None,
                 enclosures=None,
                 **kwargs):
        """
        Add an item to the feed. All args are expected to be strings except
        pubdate and updateddate, which are datetime.datetime objects, and
        enclosures, which is an iterable of instances of the Enclosure class.
        """
        def to_str(s):
            return str(s) if s is not None else s

        categories = categories and [to_str(c) for c in categories]
        self.items.append({
            'title': to_str(title),
            'link': iri_to_uri(link),
            'description': to_str(description),
            'author_email': to_str(author_email),
            'author_name': to_str(author_name),
            'author_link': iri_to_uri(author_link),
            'pubdate': pubdate,
            'updateddate': updateddate,
            'comments': to_str(comments),
            'unique_id': to_str(unique_id),
            'unique_id_is_permalink': unique_id_is_permalink,
            'enclosures': enclosures or (),
            'categories': categories or (),
            'item_copyright': to_str(item_copyright),
            'ttl': to_str(ttl),
            **kwargs,
        })
Ejemplo n.º 7
0
def _generate_cache_key(request, method, headerlist, key_prefix):
    """Return a cache key from the headers given in the header list."""
    ctx = hashlib.md5()
    for header in headerlist:
        value = request.META.get(header)
        if value is not None:
            ctx.update(force_bytes(value))
    url = hashlib.md5(force_bytes(iri_to_uri(request.build_absolute_uri())))
    cache_key = 'views.decorators.cache.cache_page.%s.%s.%s.%s' % (
        key_prefix, method, url.hexdigest(), ctx.hexdigest())
    return _i18n_cache_key_suffix(request, cache_key)
Ejemplo n.º 8
0
    def __init__(self,
                 title,
                 link,
                 description,
                 language=None,
                 author_email=None,
                 author_name=None,
                 author_link=None,
                 subtitle=None,
                 categories=None,
                 feed_url=None,
                 feed_copyright=None,
                 feed_guid=None,
                 ttl=None,
                 **kwargs):
        def to_str(s):
            return str(s) if s is not None else s

        categories = categories and [str(c) for c in categories]
        self.feed = {
            'title': to_str(title),
            'link': iri_to_uri(link),
            'description': to_str(description),
            'language': to_str(language),
            'author_email': to_str(author_email),
            'author_name': to_str(author_name),
            'author_link': iri_to_uri(author_link),
            'subtitle': to_str(subtitle),
            'categories': categories or (),
            'feed_url': iri_to_uri(feed_url),
            'feed_copyright': to_str(feed_copyright),
            'id': feed_guid or link,
            'ttl': to_str(ttl),
            **kwargs,
        }
        self.items = []
Ejemplo n.º 9
0
def iriencode(value):
    """Escape an IRI value for use in a URL."""
    return iri_to_uri(value)
Ejemplo n.º 10
0
 def get_absolute_url(self):
     # Handle script prefix manually because we bypass reverse()
     return iri_to_uri(get_script_prefix().rstrip('/') + self.url)
Ejemplo n.º 11
0
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
    if urlconf is None:
        urlconf = get_urlconf()
    resolver = get_resolver(urlconf)
    args = args or []
    kwargs = kwargs or {}

    prefix = get_script_prefix()

    if not isinstance(viewname, str):
        view = viewname
    else:
        parts = viewname.split(':')
        parts.reverse()
        view = parts[0]
        path = parts[1:]

        if current_app:
            current_path = current_app.split(':')
            current_path.reverse()
        else:
            current_path = None

        resolved_path = []
        ns_pattern = ''
        ns_converters = {}
        while path:
            ns = path.pop()
            current_ns = current_path.pop() if current_path else None
            # Lookup the name to see if it could be an app identifier.
            try:
                app_list = resolver.app_dict[ns]
                # Yes! Path part matches an app in the current Resolver.
                if current_ns and current_ns in app_list:
                    # If we are reversing for a particular app, use that
                    # namespace.
                    ns = current_ns
                elif ns not in app_list:
                    # The name isn't shared by one of the instances (i.e.,
                    # the default) so pick the first instance as the default.
                    ns = app_list[0]
            except KeyError:
                pass

            if ns != current_ns:
                current_path = None

            try:
                extra, resolver = resolver.namespace_dict[ns]
                resolved_path.append(ns)
                ns_pattern = ns_pattern + extra
                ns_converters.update(resolver.pattern.converters)
            except KeyError as key:
                if resolved_path:
                    raise NoReverseMatch(
                        "%s is not a registered namespace inside '%s'" %
                        (key, ':'.join(resolved_path))
                    )
                else:
                    raise NoReverseMatch("%s is not a registered namespace" % key)
        if ns_pattern:
            resolver = get_ns_resolver(ns_pattern, resolver, tuple(ns_converters.items()))

    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
Ejemplo n.º 12
0
 def __init__(self, url, length, mime_type):
     "All args are expected to be strings"
     self.length, self.mime_type = length, mime_type
     self.url = iri_to_uri(url)
Ejemplo n.º 13
0
def _generate_cache_header_key(key_prefix, request):
    """Return a cache key for the header cache."""
    url = hashlib.md5(force_bytes(iri_to_uri(request.build_absolute_uri())))
    cache_key = 'views.decorators.cache.cache_header.%s.%s' % (key_prefix,
                                                               url.hexdigest())
    return _i18n_cache_key_suffix(request, cache_key)