django.utils.six.moves.urllib.parse.urljoin

Here are the examples of the python api django.utils.six.moves.urllib.parse.urljoin taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

28 Examples 7

Example 1

Project: django-systemjs Source File: test_templatetags.py
    @override_settings(SYSTEMJS_ENABLED=True, SYSTEMJS_OUTPUT_DIR='SJ')
    def test_script_tag_attributes(self):
        template = """{% load system_tags %}{% systemjs_import 'myapp/main' async foo="bar" %}"""
        template = django_engine.from_string(template)
        rendered = template.render(self.context)
        expected_url = urljoin(settings.STATIC_URL, 'SJ/myapp/main.js')
        self.assertHTMLEqual(
            rendered,
            """<script async foo="bar" type="text/javascript" src="{0}"></script>""".format(expected_url)
        )

Example 2

Project: PyClassLessons Source File: widgets.py
    def absolute_path(self, path, prefix=None):
        if path.startswith(('http://', 'https://', '/')):
            return path
        if prefix is None:
            if settings.STATIC_URL is None:
                # backwards compatibility
                prefix = settings.MEDIA_URL
            else:
                prefix = settings.STATIC_URL
        return urljoin(prefix, path)

Example 3

Project: PyClassLessons Source File: request.py
Function: build_absolute_uri
    def build_absolute_uri(self, location=None):
        """
        Builds an absolute URI from the location and the variables available in
        this request. If no location is specified, the absolute URI is built on
        ``request.get_full_path()``.
        """
        if not location:
            location = self.get_full_path()
        if not absolute_http_url_re.match(location):
            current_uri = '%s://%s%s' % (self.scheme,
                                         self.get_host(), self.path)
            location = urljoin(current_uri, location)
        return iri_to_uri(location)

Example 4

Project: django-shop Source File: product.py
Function: get_absolute_url
    def get_absolute_url(self):
        """
        Return the absolute URL of a product
        """
        # sorting by highest level, so that the canonical URL
        # associates with the most generic category
        cms_page = self.cms_pages.order_by('depth').last()
        if cms_page is None:
            return urljoin('/category-not-assigned/', self.slug)
        return urljoin(cms_page.get_absolute_url(), self.slug)

Example 5

Project: reviewboard Source File: server.py
def build_server_url(*args, **kwargs):
    """Build an absolute URL containing the full URL to the server.

    All additional arguments passed will be appended as paths to the URL.
    """
    return urljoin(get_server_url(**kwargs), *args)

Example 6

Project: hue Source File: basehttp.py
    def __init__(self, *args, **kwargs):
        from django.conf import settings
        self.admin_static_prefix = urljoin(settings.STATIC_URL, 'admin/')
        # We set self.path to avoid crashes in log_message() on unsupported
        # requests (like "OPTIONS").
        self.path = ''
        self.style = color_style()
        super(WSGIRequestHandler, self).__init__(*args, **kwargs)

Example 7

Project: hue Source File: widgets.py
    def absolute_path(self, path, prefix=None):
        if path.startswith(('http://', 'https://', '/')):
            return path
        if prefix is None:
            if settings.STATIC_URL is None:
                 # backwards compatibility
                prefix = settings.MEDIA_URL
            else:
                prefix = settings.STATIC_URL
        return urljoin(prefix, path)

Example 8

Project: hue Source File: request.py
    def build_absolute_uri(self, location=None):
        """
        Builds an absolute URI from the location and the variables available in
        this request. If no location is specified, the absolute URI is built on
        ``request.get_full_path()``.
        """
        if not location:
            location = self.get_full_path()
        if not absolute_http_url_re.match(location):
            current_uri = '%s://%s%s' % ('https' if self.is_secure() else 'http',
                                         self.get_host(), self.path)
            location = urljoin(current_uri, location)
        return iri_to_uri(location)

Example 9

Project: django Source File: storage.py
Function: url
    def url(self, name):
        if self.base_url is None:
            raise ValueError("This file is not accessible via a URL.")
        url = filepath_to_uri(name)
        if url is not None:
            url = url.lstrip('/')
        return urljoin(self.base_url, url)

Example 10

Project: django Source File: static.py
Function: handle_simple
    @classmethod
    def handle_simple(cls, path):
        if apps.is_installed('django.contrib.staticfiles'):
            from django.contrib.staticfiles.storage import staticfiles_storage
            return staticfiles_storage.url(path)
        else:
            return urljoin(PrefixNode.handle_simple("STATIC_URL"), path)

Example 11

Project: django-s3-storage Source File: storage.py
    def url(self, name):
        """
        Returns an absolute URL where the file's contents can be accessed
        directly by a Web browser.
        """
        if self.aws_s3_public_url:
            return urljoin(self.aws_s3_public_url, filepath_to_uri(name))
        return self._generate_url(name)

Example 12

Project: boards-backend Source File: boards_web_static.py
@register.simple_tag(takes_context=True)
def boards_web_static(context, path=None):
    if settings.ENVIRONMENT != 'DEVELOPMENT':
        request = context['request']

        boards_web_client_version = settings.BOARDS_WEB_CLIENT_VERSION
        client_version = request.GET.get(
            'clientVersion', boards_web_client_version)

        if not path:
            path = ''

        path = '/{}/{}'.format(client_version, path)

    return urljoin(settings.BOARDS_WEB_STATIC_URL, path)

Example 13

Project: PyClassLessons Source File: storage.py
    def url(self, name):
        if self.base_url is None:
            raise ValueError("This file is not accessible via a URL.")
        return urljoin(self.base_url, filepath_to_uri(name))

Example 14

Project: PyClassLessons Source File: static.py
Function: handle_simple
    @classmethod
    def handle_simple(cls, path):
        return urljoin(PrefixNode.handle_simple("STATIC_URL"), path)

Example 15

Project: dj-libcloud Source File: storage.py
    def url(self, name):
        provider_type = self.provider['type'].lower()
        obj = self._get_object(name)
        if not obj:
            return None
        try:
            # currently only Cloudfiles supports it
            url = self.driver.get_object_cdn_url(obj)
        except NotImplementedError as e:
            object_path = '%s/%s' % (self.bucket, obj.name)
            if 's3' in provider_type:
                base_url = 'http://%s' % self.driver.connection.host
                url = urljoin(base_url, object_path)
            elif 'google' in provider_type:
                url = urljoin('//storage.googleapis.com', object_path)
            elif 'azure' in provider_type:
                base_url = ('http://%s.blob.core.windows.net' %
                            self.provider['user'])
                url = urljoin(base_url, object_path)
            else:
                raise e
        if self.secure:
            if 'cloudfiles' in provider_type:
                parsed_url = urlparse(url)
                if parsed_url.scheme != 'http':
                    return url
                split_netloc = parsed_url.netloc.split('.')
                split_netloc[1] = 'ssl'
                url = urlunparse(
                    'https',
                    '.'.join(split_netloc),
                    parsed_url.path,
                    parsed_url.params, parsed_url.query,
                    parsed_url.fragment
                )
            if ('s3' in provider_type or
                    'google' in provider_type or
                    'azure' in provider_type):
                url = url.replace('http://', 'https://')
        return url

Example 16

Project: django-shop Source File: order.py
Function: get_absolute_url
    def get_absolute_url(self):
        """
        Returns the URL for the detail view of this order
        """
        return urljoin(OrderModel.objects.get_summary_url(), self.get_number())

Example 17

Project: reviewboard Source File: github.py
    def get_repository_hook_instructions(self, request, repository):
        """Returns instructions for setting up incoming webhooks."""
        plan = repository.extra_data['repository_plan']
        add_webhook_url = urljoin(
            self.account.hosting_url or 'https://github.com/',
            '%s/%s/settings/hooks/new'
            % (self._get_repository_owner_raw(plan, repository.extra_data),
               self._get_repository_name_raw(plan, repository.extra_data)))

        webhook_endpoint_url = build_server_url(local_site_reverse(
            'github-hooks-close-submitted',
            local_site=repository.local_site,
            kwargs={
                'repository_id': repository.pk,
                'hosting_service_id': repository.hosting_account.service_name,
            }))

        example_id = 123
        example_url = build_server_url(local_site_reverse(
            'review-request-detail',
            local_site=repository.local_site,
            kwargs={
                'review_request_id': example_id,
            }))

        return render_to_string(
            'hostingsvcs/github/repo_hook_instructions.html',
            RequestContext(request, {
                'example_id': example_id,
                'example_url': example_url,
                'repository': repository,
                'server_url': get_server_url(),
                'add_webhook_url': add_webhook_url,
                'webhook_endpoint_url': webhook_endpoint_url,
                'hook_uuid': repository.get_or_create_hooks_uuid(),
            }))

Example 18

Project: reviewboard Source File: email.py
def send_review_mail(user, review_request, subject, in_reply_to,
                     to_field, cc_field, text_template_name,
                     html_template_name, context=None, extra_headers=None):
    """Format and send an e-mail out.

    Args:
        user (django.contrib.auth.models.User):
            The user who is sending the e-mail.

        review_request (reviewboard.reviews.models.ReviewRequest):
            The review request that the e-mail is about.

        subject (unicode):
            The subject of the e-mail address.

        in_reply_to (unicode):
            The e-mail message ID for threading.

        to_field (list):
            The recipients to send the e-mail to. This should be a list of
            :py:class:`Users <django.contrib.auth.models.User>` and
            :py:class:`Groups <reviewboard.reviews.models.Group>`.

        cc_field (list):
            The addresses to be CC'ed on the e-mail. This should be a list of
            :py:class:`Users <django.contrib.auth.models.User>` and
            :py:class:`Groups <reviewboard.reviews.models.Group>`.

        text_template_name (unicode):
            The name for the text e-mail template.

        html_template_name (unicode):
            The name for the HTML e-mail template.

        context (dict):
            Optional extra context to provide to the template.

        extra_headers (dict):
            Either a dict or
            :py:class:`~django.utils.datastructures.MultiValueDict` providing
            additional headers to send with the e-mail.

    Returns:
        unicode: The resulting e-mail message ID.
    """
    current_site = Site.objects.get_current()
    local_site = review_request.local_site
    from_email = build_email_address_for_user(user)

    to_field = recipients_to_addresses(to_field, review_request.id)
    cc_field = recipients_to_addresses(cc_field, review_request.id) - to_field

    if not user.should_send_own_updates():
        user_email = build_email_address_for_user(user)
        to_field.discard(user_email)
        cc_field.discard(user_email)

    if not to_field and not cc_field:
        # Nothing to send.
        return

    siteconfig = current_site.config.get()
    domain_method = siteconfig.get("site_domain_method")

    if not context:
        context = {}

    context['user'] = user
    context['domain'] = current_site.domain
    context['domain_method'] = domain_method
    context['review_request'] = review_request

    if review_request.local_site:
        context['local_site_name'] = review_request.local_site.name

    text_body = render_to_string(text_template_name, context)
    html_body = render_to_string(html_template_name, context)

    base_url = get_server_url(local_site=local_site)

    headers = MultiValueDict({
        'X-ReviewBoard-URL': [base_url],
        'X-ReviewRequest-URL': [urljoin(base_url,
                                        review_request.get_absolute_url())],
        'X-ReviewGroup': [', '.join(group.name for group in
                                    review_request.target_groups.all())],
    })

    if extra_headers:
        if not isinstance(extra_headers, MultiValueDict):
            extra_headers = MultiValueDict(
                (key, [value])
                for (key, value) in six.iteritems(extra_headers)
            )

        headers.update(extra_headers)

    if review_request.repository:
        headers['X-ReviewRequest-Repository'] = review_request.repository.name

    latest_diffset = review_request.get_latest_diffset()

    if latest_diffset:
        modified_files = set()

        for filediff in latest_diffset.files.all():
            if filediff.deleted or filediff.copied or filediff.moved:
                modified_files.add(filediff.source_file)

            if filediff.is_new or filediff.copied or filediff.moved:
                modified_files.add(filediff.dest_file)

        for filename in modified_files:
            headers.appendlist('X-ReviewBoard-Diff-For', filename)

    subject = subject.strip()
    to_field = list(to_field)
    cc_field = list(cc_field)

    if settings.DEFAULT_FROM_EMAIL:
        sender = build_email_address(full_name=user.get_full_name(),
                                     email=settings.DEFAULT_FROM_EMAIL)
    else:
        sender = None

    message = EmailMessage(subject=subject,
                           text_body=text_body.encode('utf-8'),
                           html_body=html_body.encode('utf-8'),
                           from_email=from_email,
                           sender=sender,
                           to=to_field,
                           cc=cc_field,
                           in_reply_to=in_reply_to,
                           headers=headers)

    try:
        message.send()
    except Exception:
        logging.exception("Error sending e-mail notification with subject "
                          "'%s' on behalf of '%s' to '%s'",
                          subject,
                          from_email,
                          ','.join(to_field + cc_field))

    return message.message_id

Example 19

Project: Django--an-app-at-a-time Source File: request.py
    def build_absolute_uri(self, location=None):
        """
        Builds an absolute URI from the location and the variables available in
        this request. If no ``location`` is specified, the absolute URI is
        built on ``request.get_full_path()``. Anyway, if the location is
        absolute, it is simply converted to an RFC 3987 compliant URI and
        returned and if location is relative or is scheme-relative (i.e.,
        ``//example.com/``), it is urljoined 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 20

Project: django-systemjs Source File: test_templatetags.py
Function: test_normal
    @override_settings(SYSTEMJS_ENABLED=True, SYSTEMJS_OUTPUT_DIR='SJ')
    def test_normal(self):
        rendered = self._render()
        expected_url = urljoin(settings.STATIC_URL, 'SJ/myapp/main.js')
        self.assertEqual(rendered, """<script type="text/javascript" src="{0}"></script>""".format(expected_url))

Example 21

Project: django-rest-social-auth Source File: views.py
    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
        user = self.request.backend.complete(user=user)
        return user

Example 22

Project: django-cms Source File: conf.py
Function: get_media_url
@default('CMS_MEDIA_URL')
def get_media_url():
    return urljoin(settings.MEDIA_URL, get_cms_setting('MEDIA_PATH'))

Example 23

Project: django Source File: client.py
    def _handle_redirects(self, response, **extra):
        "Follows any redirects by requesting responses from the server using GET."

        response.redirect_chain = []
        while response.status_code in (301, 302, 303, 307):
            response_url = response.url
            redirect_chain = response.redirect_chain
            redirect_chain.append((response_url, response.status_code))

            url = urlsplit(response_url)
            if url.scheme:
                extra['wsgi.url_scheme'] = url.scheme
            if url.hostname:
                extra['SERVER_NAME'] = url.hostname
            if url.port:
                extra['SERVER_PORT'] = str(url.port)

            # Prepend the request path to handle relative path redirects
            path = url.path
            if not path.startswith('/'):
                path = urljoin(response.request['PATH_INFO'], path)

            response = self.get(path, QueryDict(url.query), follow=False, **extra)
            response.redirect_chain = redirect_chain

            if redirect_chain[-1] in redirect_chain[:-1]:
                # Check that we're not redirecting to somewhere we've already
                # been to, to prevent loops.
                raise RedirectCycleError("Redirect loop detected.", last_response=response)
            if len(redirect_chain) > 20:
                # Such a lengthy chain likely also means a loop, but one with
                # a growing path, changing view, or changing query argument;
                # 20 is the value of "network.http.redirection-limit" from Firefox.
                raise RedirectCycleError("Too many redirects.", last_response=response)

        return response

Example 24

Project: django-sass-processor Source File: processor.py
    def __call__(self, path):
        basename, ext = os.path.splitext(path)
        filename = find_file(path)
        if filename is None:
            raise FileNotFoundError("Unable to locate file {path}".format(path=path))

        if ext not in self.sass_extensions:
            # return the given path, since it ends neither in `.scss` nor in `.sass`
            return urljoin(self.prefix, path)

        # compare timestamp of sourcemap file with all its dependencies, and check if we must recompile
        css_filename = basename + '.css'
        url = urljoin(self.prefix, css_filename)
        if not self.processor_enabled:
            return url
        sourcemap_filename = css_filename + '.map'
        if self.is_latest(sourcemap_filename):
            return url

        # with offline compilation, raise an error, if css file could not be found.
        if sass is None:
            msg = "Offline compiled file `{}` is missing and libsass has not been installed."
            raise ImproperlyConfigured(msg.format(css_filename))

        # add a function to be used from inside SASS
        custom_functions = {'get-setting': get_setting}

        # otherwise compile the SASS/SCSS file into .css and store it
        sourcemap_url = self.storage.url(sourcemap_filename)
        compile_kwargs = {
            'filename': filename,
            'source_map_filename': sourcemap_url,
            'include_paths': self.include_paths + APPS_INCLUDE_DIRS,
            'custom_functions': custom_functions,
        }
        if self.sass_precision:
            compile_kwargs['precision'] = self.sass_precision
        if self.sass_output_style:
            compile_kwargs['output_style'] = self.sass_output_style
        content, sourcemap = sass.compile(**compile_kwargs)
        content = force_bytes(content)
        sourcemap = force_bytes(sourcemap)
        if self.storage.exists(css_filename):
            self.storage.delete(css_filename)
        self.storage.save(css_filename, ContentFile(content))
        if self.storage.exists(sourcemap_filename):
            self.storage.delete(sourcemap_filename)
        self.storage.save(sourcemap_filename, ContentFile(sourcemap))
        return url

Example 25

Project: djangocms-cascade Source File: models.py
    def get_stylesheet_url(self):
        icon_font_url = os.path.relpath(CMSPLUGIN_CASCADE['icon_font_root'], settings.MEDIA_ROOT)
        parts = (icon_font_url, self.font_folder, 'css', 'fontello.css')
        return urljoin(settings.MEDIA_URL, '/'.join(parts))

Example 26

Project: django-product-details Source File: update_product_details.py
Function: download_directory
    def download_directory(self, dir=''):
        # Grab list of JSON files from server.
        src = urljoin(self.PROD_DETAILS_URL, dir)
        log.debug('Grabbing list of JSON files from the server from %s' % src)

        json_files = self.get_file_list(dir)
        if not json_files:
            return

        # Grab all modified JSON files from server and replace them locally.
        had_errors = False
        for json_file in json_files:
            if not self.download_json_file(urljoin(dir, json_file)):
                had_errors = True

        if had_errors:
            log.warn('Update run had errors, not storing "last updated" '
                     'timestamp.')
        else:
            # Save Last-Modified timestamp to detect updates against next time.
            log.debug('Writing last-updated timestamp (%s).' % (
                self.last_mod_response))
            self._storage.update(dir or '/', '', self.last_mod_response)

Example 27

Project: django-product-details Source File: update_product_details.py
Function: get_file_list
    def get_file_list(self, dir):
        """
        Get list of files to be updated from the server.

        If no files have been modified, returns an empty list.
        """
        # If not forced: Read last updated timestamp
        src = urljoin(self.PROD_DETAILS_URL, dir)
        self.last_update_local = None
        headers = {}

        if not self.options['force']:
            self.last_update_local = self._storage.last_modified(dir or '/')
            if self.last_update_local:
                headers = {'If-Modified-Since': self.last_update_local}
                log.debug('Found last update timestamp: %s' % (
                    self.last_update_local))
            else:
                log.info('No last update timestamp found.')

        # Retrieve file list if modified since last update
        try:
            resp = requests.get(src, headers=headers)
        except RequestException as e:
            raise CommandError('Could not retrieve file list: %s' % e)

        if resp.status_code == requests.codes.not_modified:
            log.info('{} were up to date.'.format(
                'Regions' if dir == 'regions/' else 'Product Details'))
            return []

        # Remember Last-Modified header.
        self.last_mod_response = resp.headers.get('Last-Modified')

        json_files = set(re.findall(r'href="([^"]+.json)"', resp.text))
        return json_files

Example 28

Project: django-product-details Source File: update_product_details.py
    def download_json_file(self, json_file):
        """
        Downloads a JSON file off the server, checks its validity, then drops
        it into the target dir.

        Returns True on success, False otherwise.
        """
        log.info('Updating %s from server' % json_file)

        if not self.options['force']:
            headers = {'If-Modified-Since': self._storage.last_modified(json_file)}
        else:
            headers = {}

        # Grab JSON data if modified
        try:
            url = urljoin(self.PROD_DETAILS_URL, json_file)
            resp = requests.get(url, headers=headers)
        except RequestException as e:
            log.warn('Error retrieving %s: %s' % (json_file, e))
            return False

        if resp.status_code == requests.codes.not_modified:
            log.debug('%s was not modified.' % json_file)
            return True

        # Empty results are fishy
        if not resp.text:
            log.warn('JSON source for %s was empty. Cowardly denying to '
                     'import empty data.' % json_file)
            return False

        # Try parsing the file, import if it's valid JSON.
        try:
            resp.json()
        except ValueError:
            log.warn('Could not parse JSON data from %s. Skipping.' % json_file)
            return False

        # Write JSON data to HD.
        log.debug('Writing new copy of %s.' % json_file)
        self._storage.update(json_file, resp.text, resp.headers.get('Last-Modified'))

        return True