Skip to content

Commit

Permalink
Merge pull request #18 from yanasirina/redirect
Browse files Browse the repository at this point in the history
redirect response
  • Loading branch information
daronenko authored Dec 8, 2024
2 parents 821367f + 6924bd4 commit 648a157
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion playground/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def html_example(_request):
@router.get('/hello')
def get_example(request):
logger.info(f'got {request=}')
return web.responses.JsonResponse({'message': 'hello, world!'})
return web.responses.RedirectResponse('/main')


@router.post('/hello', middlewares=[ExampleMiddleware])
Expand Down
20 changes: 20 additions & 0 deletions web/responses.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from enum import Enum
from http import HTTPStatus

from webob import Response as _Response
from jinja2 import Environment, FileSystemLoader
Expand Down Expand Up @@ -26,3 +27,22 @@ def __init__(self, template_path: str, context: dict, *args, templates_dir: str
template = env.get_template(template_path)
rendered_html = template.render(context)
super().__init__(*args, body=rendered_html, content_type=ContentType.HTML.value, **kwargs)


class RedirectResponse(Response):
def __init__(
self,
location: str,
*args,
body: dict | None = None,
status: HTTPStatus = HTTPStatus.MOVED_PERMANENTLY,
**kwargs,
):
super().__init__(*args, **kwargs)
self.status = status
self.headers['Location'] = location

if body:
self.json_body = body
else:
self.body = b""

0 comments on commit 648a157

Please sign in to comment.