Beispiel #1
0
    async def _handler(request, file_uri=None):
        # Using this to determine if the URL is trying to break out of the path
        # served.  os.path.realpath seems to be very slow
        if file_uri and '../' in file_uri:
            raise InvalidUsage("Invalid URL")
        # Merge served directory and requested file if provided
        # Strip all / that in the beginning of the URL to help prevent python
        # from herping a derp and treating the uri as an absolute path
        root_path = file_path = file_or_directory
        if file_uri:
            file_path = path.join(file_or_directory,
                                  sub('^[/]*', '', file_uri))

        # URL decode the path sent by the browser otherwise we won't be able to
        # match filenames which got encoded (filenames with spaces etc)
        file_path = path.abspath(unquote(file_path))
        if not file_path.startswith(root_path):
            raise FileNotFound('File not found',
                               path=file_or_directory,
                               relative_url=file_uri)
        try:
            headers = {}
            # Check if the client has been sent this file before
            # and it has not been modified since
            stats = None
            if use_modified_since:
                stats = await stat(file_path)
                modified_since = strftime('%a, %d %b %Y %H:%M:%S GMT',
                                          gmtime(stats.st_mtime))
                if request.headers.get('If-Modified-Since') == modified_since:
                    return HTTPResponse(status=304)
                headers['Last-Modified'] = modified_since
            _range = None
            if use_content_range:
                _range = None
                if not stats:
                    stats = await stat(file_path)
                headers['Accept-Ranges'] = 'bytes'
                headers['Content-Length'] = str(stats.st_size)
                if request.method != 'HEAD':
                    try:
                        _range = ContentRangeHandler(request, stats)
                    except HeaderNotFound:
                        pass
                    else:
                        del headers['Content-Length']
                        for key, value in _range.headers.items():
                            headers[key] = value
            if request.method == 'HEAD':
                return HTTPResponse(headers=headers,
                                    content_type=guess_type(file_path)[0]
                                    or 'text/plain')
            else:
                return await file(file_path, headers=headers, _range=_range)
        except ContentRangeError:
            raise
        except Exception:
            raise FileNotFound('File not found',
                               path=file_or_directory,
                               relative_url=file_uri)
Beispiel #2
0
 async def get_local_image(image_name):
     static_image = os.path.join(BASIC_PATH,
                                 'static/temp_image/{}').format(image_name)
     if not os.path.isfile(static_image):
         raise FileNotFound('File not found',
                            path=static_image,
                            relative_url=None)
     image = Image.open(static_image)
     image = image.convert('RGBA')
     return image
Beispiel #3
0
    async def _static_request_handler(
        self,
        file_or_directory,
        use_modified_since,
        use_content_range,
        stream_large_files,
        request,
        content_type=None,
        __file_uri__=None,
    ):
        # Using this to determine if the URL is trying to break out of the path
        # served.  os.path.realpath seems to be very slow
        if __file_uri__ and "../" in __file_uri__:
            raise InvalidUsage("Invalid URL")
        # Merge served directory and requested file if provided
        # Strip all / that in the beginning of the URL to help prevent python
        # from herping a derp and treating the uri as an absolute path
        root_path = file_path = file_or_directory
        if __file_uri__:
            file_path = path.join(file_or_directory,
                                  sub("^[/]*", "", __file_uri__))

        # URL decode the path sent by the browser otherwise we won't be able to
        # match filenames which got encoded (filenames with spaces etc)
        file_path = path.abspath(unquote(file_path))
        if not file_path.startswith(path.abspath(unquote(root_path))):
            error_logger.exception(
                f"File not found: path={file_or_directory}, "
                f"relative_url={__file_uri__}")
            raise FileNotFound(
                "File not found",
                path=file_or_directory,
                relative_url=__file_uri__,
            )
        try:
            headers = {}
            # Check if the client has been sent this file before
            # and it has not been modified since
            stats = None
            if use_modified_since:
                stats = await stat_async(file_path)
                modified_since = strftime("%a, %d %b %Y %H:%M:%S GMT",
                                          gmtime(stats.st_mtime))
                if (request.headers.getone("if-modified-since",
                                           None) == modified_since):
                    return HTTPResponse(status=304)
                headers["Last-Modified"] = modified_since
            _range = None
            if use_content_range:
                _range = None
                if not stats:
                    stats = await stat_async(file_path)
                headers["Accept-Ranges"] = "bytes"
                headers["Content-Length"] = str(stats.st_size)
                if request.method != "HEAD":
                    try:
                        _range = ContentRangeHandler(request, stats)
                    except HeaderNotFound:
                        pass
                    else:
                        del headers["Content-Length"]
                        for key, value in _range.headers.items():
                            headers[key] = value

            if "content-type" not in headers:
                content_type = (content_type or guess_type(file_path)[0]
                                or DEFAULT_HTTP_CONTENT_TYPE)

                if "charset=" not in content_type and (
                        content_type.startswith("text/")
                        or content_type == "application/javascript"):
                    content_type += "; charset=utf-8"

                headers["Content-Type"] = content_type

            if request.method == "HEAD":
                return HTTPResponse(headers=headers)
            else:
                if stream_large_files:
                    if type(stream_large_files) == int:
                        threshold = stream_large_files
                    else:
                        threshold = 1024 * 1024

                    if not stats:
                        stats = await stat_async(file_path)
                    if stats.st_size >= threshold:
                        return await file_stream(file_path,
                                                 headers=headers,
                                                 _range=_range)
                return await file(file_path, headers=headers, _range=_range)
        except ContentRangeError:
            raise
        except FileNotFoundError:
            raise FileNotFound(
                "File not found",
                path=file_or_directory,
                relative_url=__file_uri__,
            )
        except Exception:
            error_logger.exception(f"Exception in static request handler:\
 path={file_or_directory}, "
                                   f"relative_url={__file_uri__}")
Beispiel #4
0
    async def _handler(request, file_uri=None):
        # Using this to determine if the URL is trying to break out of the path
        # served.  os.path.realpath seems to be very slow
        if file_uri and "../" in file_uri:
            raise InvalidUsage("Invalid URL")
        # Merge served directory and requested file if provided
        # Strip all / that in the beginning of the URL to help prevent python
        # from herping a derp and treating the uri as an absolute path
        root_path = file_path = file_or_directory
        if file_uri:
            file_path = path.join(file_or_directory,
                                  sub("^[/]*", "", file_uri))

        # URL decode the path sent by the browser otherwise we won't be able to
        # match filenames which got encoded (filenames with spaces etc)
        file_path = path.abspath(unquote(file_path))
        if not file_path.startswith(path.abspath(unquote(root_path))):
            raise FileNotFound("File not found",
                               path=file_or_directory,
                               relative_url=file_uri)
        try:
            headers = {}
            # Check if the client has been sent this file before
            # and it has not been modified since
            stats = None
            if use_modified_since:
                stats = await stat_async(file_path)
                modified_since = strftime("%a, %d %b %Y %H:%M:%S GMT",
                                          gmtime(stats.st_mtime))
                if request.headers.get("If-Modified-Since") == modified_since:
                    return HTTPResponse(status=304)
                headers["Last-Modified"] = modified_since
            _range = None
            if use_content_range:
                _range = None
                if not stats:
                    stats = await stat_async(file_path)
                headers["Accept-Ranges"] = "bytes"
                headers["Content-Length"] = str(stats.st_size)
                if request.method != "HEAD":
                    try:
                        _range = ContentRangeHandler(request, stats)
                    except HeaderNotFound:
                        pass
                    else:
                        del headers["Content-Length"]
                        for key, value in _range.headers.items():
                            headers[key] = value
            headers["Content-Type"] = (content_type or guess_type(file_path)[0]
                                       or "text/plain")
            if request.method == "HEAD":
                return HTTPResponse(headers=headers)
            else:
                if stream_large_files:
                    if type(stream_large_files) == int:
                        threshold = stream_large_files
                    else:
                        threshold = 1024 * 1024

                    if not stats:
                        stats = await stat_async(file_path)
                    if stats.st_size >= threshold:
                        return await file_stream(file_path,
                                                 headers=headers,
                                                 _range=_range)
                return await file(file_path, headers=headers, _range=_range)
        except ContentRangeError:
            raise
        except Exception:
            raise FileNotFound("File not found",
                               path=file_or_directory,
                               relative_url=file_uri)
Beispiel #5
0
async def admin_static_route(request, str):
    file_path = os.path.join(BASIC_PATH, 'static/gpetmg/build/index.html')
    try:
        return await file(file_path)
    except Exception:
        raise FileNotFound('File not found', path=file_path, relative_url=None)
Beispiel #6
0
async def catch_all_views(request, path=''):
    file_path = os.path.join(BASIC_PATH, 'static/grouppet/build/index.html')
    try:
        return await file(file_path)
    except Exception:
        raise FileNotFound('File not found', path=file_path, relative_url=None)