Пример #1
0
async def blog(request):
    return HTTPMovedPermanently(
        '/blog/',
        headers={
            'Cache-Control': 'public, immutable, max-age=31536000',
        },
    )
Пример #2
0
async def error_middleware(request, handler):
    try:
        http_exception = getattr(request.match_info, 'http_exception', None)
        if http_exception:
            raise http_exception
        else:
            r = await handler(request)
    except HTTPException as e:
        if request.method == METH_GET and e.status == 404 and request.rel_url.raw_path.endswith(
                '/'):
            possible_path = request.rel_url.raw_path[:-1]
            for resource in request.app.router._resources:
                match_dict = resource._match(possible_path)
                if match_dict:
                    raise HTTPMovedPermanently(possible_path)
        if e.status > 310:
            await log_warning(request, e)
        raise
    except BaseException as e:
        request_logger.exception(
            '%s: %s',
            e.__class__.__name__,
            e,
            extra={
                'fingerprint': [e.__class__.__name__,
                                str(e)],
                'data': await log_extra(request)
            },
        )
        raise HTTPInternalServerError()
    else:
        if r.status > 310:
            await log_warning(request, r)
    return r
Пример #3
0
async def remove_slash_middleware(request, handler):
    """ Redirect to URL without trailing slashes midlleware. """
    if request.path.endswith('/'):
        try:
            raise HTTPMovedPermanently(request.path.rstrip('/'))
        except ValueError:
            pass
    response = await handler(request)
    return response
Пример #4
0
    async def handle_file(self,
                          request: 'web.Request',
                          filename: str,
                          from_index=None) -> 'web.Response':
        """Handle file requests."""
        try:
            filepath = self._directory.joinpath(filename).resolve()
            if not self._follow_symlinks:
                filepath.relative_to(self._directory)
        except (ValueError, FileNotFoundError) as error:
            # relatively safe
            raise HTTPNotFound() from error
        except Exception as error:
            # perm error or other kind!
            request.app.logger.exception(error)
            raise HTTPNotFound() from error

        # on opening a dir, load it's contents if allowed
        if filepath.is_dir():
            if filename.endswith('/') or not filename:
                ret = await self.handle_file(request,
                                             filename + 'index.html',
                                             from_index=filename)
            else:
                # Redirect and add trailing slash so relative links work (Issue #3140)
                new_url = request.rel_url.path + '/'
                if request.rel_url.query_string:
                    new_url += '?' + request.rel_url.query_string
                raise HTTPMovedPermanently(new_url)
        elif filepath.is_file():
            ct, encoding = mimetypes.guess_type(str(filepath))
            encoding = encoding or 'utf-8'
            if ct == 'text/html' and self.modify_html:
                if sys.version_info[0] == 3 and sys.version_info[1] <= 5:
                    # Python 3.4 and 3.5 do not accept pathlib.Path objects in calls to open()
                    filepath = str(filepath)
                with open(filepath, 'r', encoding=encoding) as fh:
                    text = fh.read()
                    text = self.transform_html(text)
                    ret = Response(text=text,
                                   content_type=ct,
                                   charset=encoding)
            else:
                ret = FileResponse(filepath, chunk_size=self._chunk_size)
        elif from_index:
            filepath = self._directory.joinpath(from_index).resolve()
            try:
                return Response(text=self._directory_as_html(filepath),
                                content_type="text/html")
            except PermissionError:
                raise HTTPForbidden
        else:
            raise HTTPNotFound

        return ret
Пример #5
0
async def static_handler(request):
    # modified from aiohttp_web_urldispatcher.StaticResource_handle
    request_path = request.match_info['path'].lstrip('/')

    directory = request.app['static_dir']
    csp_headers = request.app['csp_headers']
    if request_path == '':
        return FileResponse(directory / 'index.html', headers=csp_headers)
    elif request_path == 'sitemap.xml':
        raise HTTPMovedPermanently(
            location=f'https://{request.host}/api/sitemap.xml')

    try:
        filename = Path(request_path)
        if filename.anchor:  # pragma: no cover
            # windows only I think, but keep it just in case
            # request_path is an absolute name like
            # /static/\\machine_name\c$ or /static/D:\path
            # where the static dir is totally different
            raise HTTPNotFound()
        filepath = directory.joinpath(filename).resolve()
        filepath.relative_to(directory)
    except Exception as exc:
        # perm error or other kind!
        logger.warning('error resolving path %r', request_path, exc_info=True)
        raise HTTPNotFound() from exc

    is_file = filepath.is_file()
    if request_path.startswith('iframes/') and request_path.endswith(
            '.html') and is_file:
        new_root = request_root(request)
        content = filepath.read_text().replace('http://localhost:3000',
                                               new_root)
        # no csp header here, it's defined in the page as a http-equiv header
        return Response(text=content, content_type='text/html')
    elif is_file:
        return FileResponse(filepath, headers=csp_headers)
    elif request_path.startswith('pvt/'):
        return FileResponse(directory / 'index.html',
                            headers={
                                **csp_headers,
                                **{
                                    'X-Robots-Tag': 'noindex'
                                }
                            })
    else:
        return FileResponse(directory / 'index.html', headers=csp_headers)
Пример #6
0
async def moved(request):
    raise HTTPMovedPermanently('/')
Пример #7
0
 def redirect(request):
     """Redirect to location."""
     raise HTTPMovedPermanently(redirect_to)
Пример #8
0
async def redirect_index_zh_hant(request):
    return HTTPMovedPermanently(
        '/zh-Hant/',
        headers={
            'Cache-Control': 'public, immutable, max-age=31536000',  # 1 year
        })
Пример #9
0
async def remap_fonts(request):
    fn = request.match_info['fname']
    # remap some links so we don't need to edit Semantic files.
    return HTTPMovedPermanently('/static/ext/semantic-fonts/' + fn)
Пример #10
0
 async def handler(self, request: Request) -> Response:
     if request.method == 'GET' and request.path in self.challenges:
         return HTTPOk(body=self.challenges[request.path])
     else:
         return HTTPMovedPermanently(
             f'https://{request.host}{request.path_qs}')