django.utils.six.moves.urllib.parse.urlparse.path

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

6 Examples 7

Example 1

Project: Misago
Source File: auth.py
View license
@sensitive_post_parameters()
@never_cache
@csrf_protect
def login(request):
    if request.method == 'POST':
        redirect_to = request.POST.get('redirect_to')
        if redirect_to:
            is_redirect_safe = is_safe_url(
                url=redirect_to, host=request.get_host())
            if is_redirect_safe:
                redirect_to_path = urlparse(redirect_to).path
                return redirect(redirect_to_path)

    return redirect(settings.LOGIN_REDIRECT_URL)

Example 2

Project: boards-backend
Source File: previews.py
View license
def get_parsed_file_from_url(url):
    """
    Returns a URL's file extension, mimetype, encoding, and type.
    """
    try:
        url_path = urlparse(url).path
        file_extension = os.path.splitext(url_path)[1].lower()
        file_mimetype, file_encoding = mimetypes.guess_type(url_path)
    except:
        file_extension = None
        file_mimetype = None
        file_encoding = None

    return {
        'extension': file_extension,
        'mimetype': file_mimetype,
        'encoding': file_encoding,
        'type': file_mimetype.split('/')[0] if file_mimetype else None,
    }

Example 3

Project: wagtailmodeladmin
Source File: middleware.py
View license
    def process_request(self, request):
        """
        Ignore unnecessary actions for static file requests, posts, or ajax
        requests. We're only interested in redirecting following a 'natural'
        request redirection to the `wagtailadmin_explore_root` or
        `wagtailadmin_explore` views.
        """
        referer_url = request.META.get('HTTP_REFERER')
        return_to_index_url = request.session.get('return_to_index_url')

        try:
            if all((
                return_to_index_url,
                referer_url,
                request.method == 'GET',
                not request.is_ajax(),
                resolve(request.path).url_name in ('wagtailadmin_explore_root',
                                                   'wagtailadmin_explore'),
            )):
                perform_redirection = False
                referer_match = resolve(urlparse(referer_url).path)
                if all((
                    referer_match.namespace == 'wagtailadmin_pages',
                    referer_match.url_name in (
                        'add',
                        'edit',
                        'delete',
                        'unpublish',
                        'copy'
                    ),
                )):
                    perform_redirection = True
                elif all((
                    not referer_match.namespace,
                    referer_match.url_name in (
                        'wagtailadmin_pages_create',
                        'wagtailadmin_pages_edit',
                        'wagtailadmin_pages_delete',
                        'wagtailadmin_pages_unpublish'
                    ),
                )):
                    perform_redirection = True
                if perform_redirection:
                    del request.session['return_to_index_url']
                    return HttpResponseRedirect(return_to_index_url)

        except Resolver404:
            pass

        return None

Example 4

Project: wagtail
Source File: middleware.py
View license
    def process_response(self, request, response):
        # No need to check for a redirect for non-404 responses.
        if response.status_code != 404:
            return response

        # If a middleware before `SiteMiddleware` returned a response the
        # `site` attribute was never set, ref #2120
        if not hasattr(request, 'site'):
            return response

        # Get the path
        path = models.Redirect.normalise_path(request.get_full_path())

        # Find redirect
        redirect = get_redirect(request, path)
        if redirect is None:
            # Get the path without the query string or params
            path_without_query = urlparse(path).path

            if path == path_without_query:
                # don't try again if we know we will get the same response
                return response

            redirect = get_redirect(request, path_without_query)
            if redirect is None:
                return response

        if redirect.is_permanent:
            return http.HttpResponsePermanentRedirect(redirect.link)
        else:
            return http.HttpResponseRedirect(redirect.link)

Example 5

Project: whitenoise
Source File: django.py
View license
    def configure_from_settings(self, settings):
        # Default configuration
        self.charset = settings.FILE_CHARSET
        self.autorefresh = settings.DEBUG
        self.use_finders = settings.DEBUG
        self.static_prefix = urlparse(settings.STATIC_URL or '').path
        if settings.DEBUG:
            self.max_age = 0
        # Allow settings to override default attributes
        for attr in self.config_attrs:
            settings_key = 'WHITENOISE_{0}'.format(attr.upper())
            try:
                value = getattr(settings, settings_key)
            except AttributeError:
                pass
            else:
                value = decode_if_byte_string(value)
                setattr(self, attr, value)
        self.static_prefix = ensure_leading_trailing_slash(self.static_prefix)
        self.static_root = decode_if_byte_string(settings.STATIC_ROOT)

Example 6

Project: django-raster
Source File: parser.py
View license
    def open_raster_file(self):
        """
        Get raster source file to extract tiles from.

        This makes a local copy of rasterfile, unzips the raster and reprojects
        it into web mercator if necessary. The reprojected raster is stored for
        reuse such that reprojection does only happen once.

        The local copy of the raster is needed if files are stored on remote
        storages.
        """
        reproj, created = RasterLayerReprojected.objects.get_or_create(rasterlayer=self.rasterlayer)
        # Check if the raster has already been reprojected
        has_reprojected = reproj.rasterfile.name not in (None, '')

        # Create workdir
        raster_workdir = getattr(settings, 'RASTER_WORKDIR', None)
        self.tmpdir = tempfile.mkdtemp(dir=raster_workdir)

        # Choose source for raster data, use the reprojected version if it exists.
        if self.rasterlayer.source_url and not has_reprojected:
            url_path = urlparse(self.rasterlayer.source_url).path
            filename = url_path.split('/')[-1]
            filepath = os.path.join(self.tmpdir, filename)
            urlretrieve(self.rasterlayer.source_url, filepath)
        else:
            if has_reprojected:
                rasterfile_source = reproj.rasterfile
            else:
                rasterfile_source = self.rasterlayer.rasterfile

            if not rasterfile_source.name:
                raise RasterException('No data source found. Provide a rasterfile or a source url.')

            # Copy raster file source to local folder
            filepath = os.path.join(self.tmpdir, os.path.basename(rasterfile_source.name))
            rasterfile = open(filepath, 'wb')
            for chunk in rasterfile_source.chunks():
                rasterfile.write(chunk)
            rasterfile.close()

        # If the raster file is compressed, decompress it, otherwise try to
        # open the source file directly.
        if os.path.splitext(filepath)[1].lower() == '.zip':
            # Open and extract zipfile
            zf = zipfile.ZipFile(filepath)
            zf.extractall(self.tmpdir)

            # Remove zipfile
            os.remove(filepath)

            # Get filelist from directory
            matches = []
            for root, dirnames, filenames in os.walk(self.tmpdir):
                for filename in fnmatch.filter(filenames, '*.*'):
                    matches.append(os.path.join(root, filename))

            # Open the first raster file found in the matched files.
            self.dataset = None
            for match in matches:
                try:
                    self.dataset = GDALRaster(match)
                    break
                except GDALException:
                    pass

            # Raise exception if no file could be opened by gdal.
            if not self.dataset:
                raise RasterException('Could not open rasterfile.')
        else:
            self.dataset = GDALRaster(filepath)

        # Override srid if provided
        if self.rasterlayer.srid:
            try:
                self.dataset = GDALRaster(self.dataset.name, write=True)
            except GDALException:
                raise RasterException(
                    'Could not override srid because the driver for this '
                    'type of raster does not support write mode.'
                )
            self.dataset.srs = self.rasterlayer.srid