Python django.utils.encoding.iri_to_uri() Examples

The following are 30 code examples of django.utils.encoding.iri_to_uri(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.encoding , or try the search function .
Example #1
Source File: request.py    From bioforum with MIT License 6 votes vote down vote up
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, bulid 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):
            current_uri = '{scheme}://{host}{path}'.format(scheme=self.scheme,
                                                           host=self.get_host(),
                                                           path=self.path)
            # Join the constructed URL with the provided location, which will
            # allow the provided ``location`` to apply query strings to the
            # base path as well as override the host, if it begins with //
            location = urljoin(current_uri, location)
        return iri_to_uri(location) 
Example #2
Source File: rest.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def _get_cache_key(self, request):
        """
        Generate cache key that's exactly unique enough.

        Assumes that the response is determined by the request.method, authenticated user, and URL path.
        """
        # HTTP method
        method = request.method

        # Authenticated username
        if not request.user.is_authenticated or self.cache_ignore_auth:
            username = '*'
        else:
            username = request.user.username

        # URL path
        url = force_text(iri_to_uri(request.get_full_path()))

        # build a cache key out of that
        key = '#'.join(('CacheMixin', self.key_prefix, username, method, url))
        if len(key) > MAX_KEY_LENGTH:
            # make sure keys don't get too long
            key = key[:(MAX_KEY_LENGTH - 33)] + '-' + hashlib.md5(key.encode('utf8')).hexdigest()

        return key 
Example #3
Source File: models.py    From django-simple-pagination with MIT License 6 votes vote down vote up
def __init__(self, request, number, current_number, *args, **kwargs):
        total_number = kwargs.get('total_number')
        querystring_key = kwargs.get('querystring_key', 'page')
        label = kwargs.get('label', None)
        default_number = kwargs.get('default_number', 1)
        override_path = kwargs.get('override_path', None)
        self._request = request
        self.number = number
        self.label = utils.text(number) if label is None else label
        self.querystring_key = querystring_key

        self.is_current = number == current_number
        self.is_first = number == 1
        self.is_last = number == total_number

        self.url = utils.get_querystring_for_page(
            request, number, self.querystring_key,
            default_number=default_number)
        path = iri_to_uri(override_path or request.path)
        self.path = '{0}{1}'.format(path, self.url) 
Example #4
Source File: feedgenerator.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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 = [] 
Example #5
Source File: models.py    From django-simple-pagination with MIT License 6 votes vote down vote up
def __init__(self, request, number, current_number, *args, **kwargs):
        total_number = kwargs.get('total_number')
        querystring_key = kwargs.get('querystring_key', 'page')
        label = kwargs.get('label', None)
        default_number = kwargs.get('default_number', 1)
        override_path = kwargs.get('override_path', None)
        self._request = request
        self.number = number
        self.label = utils.text(number) if label is None else label
        self.querystring_key = querystring_key

        self.is_current = number == current_number
        self.is_first = number == 1
        self.is_last = number == total_number

        self.url = utils.get_querystring_for_page(
            request, number, self.querystring_key,
            default_number=default_number)
        path = iri_to_uri(override_path or request.path)
        self.path = '{0}{1}'.format(path, self.url) 
Example #6
Source File: base.py    From django-seo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, metadata, instances, path, site=None, language=None, subdomain=None):
        self.__metadata = metadata
        if metadata._meta.use_cache:
            if metadata._meta.use_sites and site:
                hexpath = hashlib.md5(iri_to_uri(site.domain + path).encode('utf-8')).hexdigest()
            else:
                hexpath = hashlib.md5(iri_to_uri(path).encode('utf-8')).hexdigest()
            prefix_bits = ['djangoseo', self.__metadata.__class__.__name__, hexpath]
            if metadata._meta.use_i18n:
                prefix_bits.append(language)
            if metadata._meta.use_subdomains and subdomain is not None:
                prefix_bits.append(subdomain)
            self.__cache_prefix = '.'.join(prefix_bits)
        else:
            self.__cache_prefix = None
        self.__instances_original = instances
        self.__instances_cache = [] 
Example #7
Source File: feedgenerator.py    From bioforum with MIT License 6 votes vote down vote up
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
        if categories:
            categories = [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),
        }
        self.feed.update(kwargs)
        self.items = [] 
Example #8
Source File: defaultfilters.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def iriencode(value):
    """Escapes an IRI value for use in a URL."""
    return force_text(iri_to_uri(value)) 
Example #9
Source File: feedgenerator.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
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):
        to_unicode = lambda s: force_text(s, strings_only=True)
        if categories:
            categories = [force_text(c) for c in categories]
        if ttl is not None:
            # Force ints to unicode
            ttl = force_text(ttl)
        self.feed = {
            'title': to_unicode(title),
            'link': iri_to_uri(link),
            'description': to_unicode(description),
            'language': to_unicode(language),
            'author_email': to_unicode(author_email),
            'author_name': to_unicode(author_name),
            'author_link': iri_to_uri(author_link),
            'subtitle': to_unicode(subtitle),
            'categories': categories or (),
            'feed_url': iri_to_uri(feed_url),
            'feed_copyright': to_unicode(feed_copyright),
            'id': feed_guid or link,
            'ttl': ttl,
        }
        self.feed.update(kwargs)
        self.items = [] 
Example #10
Source File: feedgenerator.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def add_item(self, title, link, description, author_email=None,
        author_name=None, author_link=None, pubdate=None, comments=None,
        unique_id=None, enclosure=None, categories=(), item_copyright=None,
        ttl=None, **kwargs):
        """
        Adds an item to the feed. All args are expected to be Python Unicode
        objects except pubdate, which is a datetime.datetime object, and
        enclosure, which is an instance of the Enclosure class.
        """
        to_unicode = lambda s: force_text(s, strings_only=True)
        if categories:
            categories = [to_unicode(c) for c in categories]
        if ttl is not None:
            # Force ints to unicode
            ttl = force_text(ttl)
        item = {
            'title': to_unicode(title),
            'link': iri_to_uri(link),
            'description': to_unicode(description),
            'author_email': to_unicode(author_email),
            'author_name': to_unicode(author_name),
            'author_link': iri_to_uri(author_link),
            'pubdate': pubdate,
            'comments': to_unicode(comments),
            'unique_id': to_unicode(unique_id),
            'enclosure': enclosure,
            'categories': categories or (),
            'item_copyright': to_unicode(item_copyright),
            'ttl': ttl,
        }
        item.update(kwargs)
        self.items.append(item) 
Example #11
Source File: static.py    From python2017 with MIT License 5 votes vote down vote up
def handle_simple(cls, name):
        try:
            from django.conf import settings
        except ImportError:
            prefix = ''
        else:
            prefix = iri_to_uri(getattr(settings, name, ''))
        return prefix 
Example #12
Source File: views.py    From python with Apache License 2.0 5 votes vote down vote up
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 
Example #13
Source File: views.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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 
Example #14
Source File: models.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_absolute_url(self):
        # Handle script prefix manually because we bypass reverse()
        return iri_to_uri(get_script_prefix().rstrip('/') + self.url) 
Example #15
Source File: filterlinks.py    From open-context-py with GNU General Public License v3.0 5 votes vote down vote up
def make_request_url(self,
                         new_rparams,
                         doc_format=''):
        """ makes request urls from the new request object
            default doc_format is '' (HTML)
        """
        url = self.base_url + self.base_search_link
        if 'path' in new_rparams:
            if new_rparams['path'] is not None \
               and new_rparams['path'] is not False:
                # context_path = iri_to_uri(new_rparams['path'])
                context_path = new_rparams['path']
                context_path = context_path.replace(' ', '+')
                url += context_path
        url += doc_format
        param_sep = '?'
        param_list = []
        for param, param_vals in new_rparams.items():
            if param != 'path':
                for val in param_vals:
                    quote_val = quote_plus(val)
                    quote_val = quote_val.replace('%7BSearchTerm%7D', '{SearchTerm}')
                    param_item = param + '=' + quote_val
                    param_list.append(param_item)
        if len(param_list) > 0:
            # keep a consistent sort order on query parameters + values.
            param_list.sort()
            url += '?' + '&'.join(param_list)
        return url 
Example #16
Source File: feedgenerator.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, url, length, mime_type):
        "All args are expected to be Python Unicode objects"
        self.length, self.mime_type = length, mime_type
        self.url = iri_to_uri(url) 
Example #17
Source File: defaultfilters.py    From python2017 with MIT License 5 votes vote down vote up
def iriencode(value):
    """Escapes an IRI value for use in a URL."""
    return force_text(iri_to_uri(value)) 
Example #18
Source File: static.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def handle_simple(cls, name):
        try:
            from django.conf import settings
        except ImportError:
            prefix = ''
        else:
            prefix = iri_to_uri(getattr(settings, name, ''))
        return prefix 
Example #19
Source File: cache.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def _generate_cache_key(request, method, headerlist, key_prefix):
    """Returns a cache key from the headers given in the header list."""
    ctx = hashlib.md5()
    for header in headerlist:
        value = request.META.get(header, None)
        if value is not None:
            ctx.update(force_bytes(value))
    path = hashlib.md5(force_bytes(iri_to_uri(request.get_full_path())))
    cache_key = 'views.decorators.cache.cache_page.%s.%s.%s.%s' % (
        key_prefix, method, path.hexdigest(), ctx.hexdigest())
    return _i18n_cache_key_suffix(request, cache_key) 
Example #20
Source File: defaultfilters.py    From python with Apache License 2.0 5 votes vote down vote up
def iriencode(value):
    """Escapes an IRI value for use in a URL."""
    return force_text(iri_to_uri(value)) 
Example #21
Source File: cache.py    From python with Apache License 2.0 5 votes vote down vote up
def _generate_cache_key(request, method, headerlist, key_prefix):
    """Returns 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) 
Example #22
Source File: feedgenerator.py    From python with Apache License 2.0 5 votes vote down vote up
def __init__(self, url, length, mime_type):
        "All args are expected to be Python Unicode objects"
        self.length, self.mime_type = length, mime_type
        self.url = iri_to_uri(url) 
Example #23
Source File: feedgenerator.py    From python with Apache License 2.0 5 votes vote down vote up
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_unicode(s):
            return force_text(s, strings_only=True)
        if categories:
            categories = [force_text(c) for c in categories]
        if ttl is not None:
            # Force ints to unicode
            ttl = force_text(ttl)
        self.feed = {
            'title': to_unicode(title),
            'link': iri_to_uri(link),
            'description': to_unicode(description),
            'language': to_unicode(language),
            'author_email': to_unicode(author_email),
            'author_name': to_unicode(author_name),
            'author_link': iri_to_uri(author_link),
            'subtitle': to_unicode(subtitle),
            'categories': categories or (),
            'feed_url': iri_to_uri(feed_url),
            'feed_copyright': to_unicode(feed_copyright),
            'id': feed_guid or link,
            'ttl': ttl,
        }
        self.feed.update(kwargs)
        self.items = [] 
Example #24
Source File: static.py    From python with Apache License 2.0 5 votes vote down vote up
def handle_simple(cls, name):
        try:
            from django.conf import settings
        except ImportError:
            prefix = ''
        else:
            prefix = iri_to_uri(getattr(settings, name, ''))
        return prefix 
Example #25
Source File: views.py    From django-rest-social-auth with MIT License 5 votes vote down vote up
def get_object(self):
        user = self.request.user
        manual_redirect_uri = self.request.auth_data.pop('redirect_uri', None)
        manual_redirect_uri = self.get_redirect_uri(manual_redirect_uri)
        if manual_redirect_uri:
            self.request.backend.redirect_uri = manual_redirect_uri
        elif DOMAIN_FROM_ORIGIN:
            origin = self.request.strategy.request.META.get('HTTP_ORIGIN')
            if origin:
                relative_path = urlparse(self.request.backend.redirect_uri).path
                url = urlparse(origin)
                origin_scheme_host = "%s://%s" % (url.scheme, url.netloc)
                location = urljoin(origin_scheme_host, relative_path)
                self.request.backend.redirect_uri = iri_to_uri(location)
        is_authenticated = user_is_authenticated(user)
        user = is_authenticated and user or None
        # skip checking state by setting following params to False
        # it is responsibility of front-end to check state
        # TODO: maybe create an additional resource, where front-end will
        # store the state before making a call to oauth provider
        # so server can save it in session and consequently check it before
        # sending request to acquire access token.
        # In case of token authentication we need a way to store an anonymous
        # session to do it.
        self.request.backend.REDIRECT_STATE = False
        self.request.backend.STATE_PARAMETER = False

        if self.oauth_v1():
            self.save_token_param_in_session()

        user = self.request.backend.complete(user=user)
        return user 
Example #26
Source File: views.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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 
Example #27
Source File: defaultfilters.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def iriencode(value):
    """Escape an IRI value for use in a URL."""
    return iri_to_uri(value) 
Example #28
Source File: response.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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) 
Example #29
Source File: request.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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) 
Example #30
Source File: request.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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 ''
        )