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: 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 #2
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 #3
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 #4
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 #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: 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 #7
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 #8
Source File: static.py    From GTDWeb 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 #9
Source File: feedgenerator.py    From GTDWeb 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 GTDWeb 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, unique_id_is_permalink=None, enclosure=None,
            categories=(), item_copyright=None, ttl=None, updateddate=None, **kwargs):
        """
        Adds an item to the feed. All args are expected to be Python Unicode
        objects except pubdate and updateddate, which are datetime.datetime
        objects, 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,
            'updateddate': updateddate,
            'comments': to_unicode(comments),
            'unique_id': to_unicode(unique_id),
            'unique_id_is_permalink': unique_id_is_permalink,
            'enclosure': enclosure,
            'categories': categories or (),
            'item_copyright': to_unicode(item_copyright),
            'ttl': ttl,
        }
        item.update(kwargs)
        self.items.append(item) 
Example #11
Source File: feedgenerator.py    From GTDWeb with GNU General Public License v2.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 #12
Source File: cache.py    From GTDWeb 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))
    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 #13
Source File: defaultfilters.py    From GTDWeb with GNU General Public License v2.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 #14
Source File: views.py    From GTDWeb with GNU General Public License v2.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://')
            or url.startswith('https://')
            or url.startswith('mailto:')):
        url = iri_to_uri('%s://%s%s' % (protocol, domain, url))
    return url 
Example #15
Source File: models.py    From GTDWeb with GNU General Public License v2.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 #16
Source File: static.py    From bioforum 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 #17
Source File: feedgenerator.py    From bioforum with MIT License 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, 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
        if categories:
            categories = [to_str(c) for c in categories]
        item = {
            '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),
        }
        item.update(kwargs)
        self.items.append(item) 
Example #18
Source File: feedgenerator.py    From bioforum with MIT License 5 votes vote down vote up
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) 
Example #19
Source File: cache.py    From bioforum with MIT License 5 votes vote down vote up
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) 
Example #20
Source File: request.py    From bioforum with MIT License 5 votes vote down vote up
def get_full_path(self, force_append_slash=False):
        # 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(self.path),
            '/' if force_append_slash and not self.path.endswith('/') else '',
            ('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) if self.META.get('QUERY_STRING', '') else ''
        ) 
Example #21
Source File: response.py    From bioforum 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 #22
Source File: defaultfilters.py    From bioforum 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 #23
Source File: views.py    From bioforum 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 #24
Source File: tests.py    From django-seo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_use_cache(self):
        """ Checks that cache is being used when use_cache is set.
            Will only work if cache backend is not dummy.
        """
        if 'dummy' not in settings.CACHE_BACKEND:
            path = '/'
            hexpath = hashlib.md5(iri_to_uri(path)).hexdigest()

            # six.text_type(seo_get_metadata(path, name="Coverage"))
            six.text_type(seo_get_metadata(path, name="WithCache"))

            self.assertEqual(cache.get('djangoseo.Coverage.%s.title' % hexpath), None)
            self.assertEqual(cache.get('djangoseo.WithCache.%s.title' % hexpath), "1234")
            self.assertEqual(cache.get('djangoseo.WithCache.%s.subtitle' % hexpath), "") 
Example #25
Source File: tests.py    From django-seo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_use_cache_site(self):
        """ Checks that the cache plays nicely with sites.
        """
        if 'dummy' not in settings.CACHE_BACKEND:
            path = '/'
            site = Site.objects.get_current()
            hexpath = hashlib.md5(iri_to_uri(site.domain + path)).hexdigest()

            # six.text_type(seo_get_metadata(path, name="Coverage"))
            six.text_type(seo_get_metadata(path, name="WithCacheSites", site=site))

            self.assertEqual(cache.get('djangoseo.Coverage.%s.title' % hexpath), None)
            self.assertEqual(cache.get('djangoseo.WithCacheSites.%s.title' % hexpath), "1234")
            self.assertEqual(cache.get('djangoseo.WithCacheSites.%s.subtitle' % hexpath), "") 
Example #26
Source File: tests.py    From django-seo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_use_cache_i18n(self):
        """ Checks that the cache plays nicely with i18n.
        """
        if 'dummy' not in settings.CACHE_BACKEND:
            path = '/'
            hexpath = hashlib.md5(iri_to_uri(path)).hexdigest()

            # six.text_type(seo_get_metadata(path, name="Coverage"))
            six.text_type(seo_get_metadata(path, name="WithCacheI18n", language='de'))

            self.assertEqual(cache.get('djangoseo.Coverage.%s.de.title' % hexpath), None)
            self.assertEqual(cache.get('djangoseo.WithCacheI18n.%s.en.title' % hexpath), None)
            self.assertEqual(cache.get('djangoseo.WithCacheI18n.%s.de.title' % hexpath), "1234")
            self.assertEqual(cache.get('djangoseo.WithCacheI18n.%s.de.subtitle' % hexpath), "") 
Example #27
Source File: tests.py    From django-seo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_use_cache_i18n_subdomain(self):
        """ Checks that the cache plays nicely with i18n and subdomain.
        """
        if 'dummy' not in settings.CACHE_BACKEND:
            path = '/'
            hexpath = hashlib.md5(iri_to_uri(path)).hexdigest()

            six.text_type(seo_get_metadata(path, name='WithSubdomains', language='ru', subdomain='msk'))

            self.assertEqual(cache.get('djangoseo.Coverage.%s.de.msk.title' % hexpath), None)
            self.assertEqual(cache.get('djangoseo.WithSubdomains.%s.en.msk.title' % hexpath), None)
            self.assertEqual(cache.get('djangoseo.WithSubdomains.%s.ru.spb.title' % hexpath), None)
            self.assertEqual(cache.get('djangoseo.WithSubdomains.%s.ru.spb.subtitle' % hexpath), None)
            self.assertEqual(cache.get('djangoseo.WithSubdomains.%s.ru.msk.title' % hexpath), '1234')
            self.assertEqual(cache.get('djangoseo.WithSubdomains.%s.ru.msk.subtitle' % hexpath), '') 
Example #28
Source File: models.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_absolute_url(self):
        return iri_to_uri(reverse(
            'resources:project_detail',
            kwargs={
                'organization': self.project.organization.slug,
                'project': self.project.slug,
                'resource': self.id,
            },
        )) 
Example #29
Source File: models.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_absolute_url(self):
        return iri_to_uri(reverse(
            'parties:detail',
            kwargs={
                'organization': self.project.organization.slug,
                'project': self.project.slug,
                'party': self.id,
            },
        )) 
Example #30
Source File: models.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_absolute_url(self):
        return iri_to_uri(reverse(
            'parties:relationship_detail',
            kwargs={
                'organization': self.project.organization.slug,
                'project': self.project.slug,
                'relationship': self.id,
            },
        ))