def test_a_response_is_created_with_the_right_headers(): response = Response('Some content', 403) assert response.content == b'Some content' assert response.status == '403 Forbidden' assert response.headers == [('Content-Type', 'text/html; charset=utf8'), ('Content-Length', '12')]
def post_article(request: Request): try: content = json.loads(request.body) except ValueError: content = {} title = content.get('title', 'undefined') return Response(f'<html><h1>Article "{title}" created!</h1></html>')
def test_the_response_gives_accurate_status(): expected_answers = ( (200, '200 OK'), (409, '409 Conflict'), (404, '404 Not Found'), ) for (code, description) in expected_answers: assert Response('Some content', status=code).status == description
@dataclass class CompiledRoute: regex: str view: Callable options: dict def call_view(request: Request, route_declarations: list) -> Response: routes = _compile_routes(route_declarations) for route in routes: if matches := re.match(route.regex, request.path): if 'methods' not in route.options or request.method in route.options[ 'methods']: return route.view(request=request, **matches.groupdict()) return Response('Not found', 404) def _compile_routes(route_declarations: list): compiled_routes = [] for declaration in route_declarations: regex = re.sub(r'{([^}]+)}', r'(?P<\g<1>>[a-zA-Z0-9%_-]+)', declaration.path) regex = r'^' + regex + r'$' compiled_routes.append( CompiledRoute(regex, declaration.view, declaration.options)) return compiled_routes
def article(request: Request, article_slug: str): return Response(f'<html><h1>Article, {article_slug}</h1></html>')
def view_home(request: Request) -> Response: return Response('Homepage')
def view_article(request: Request, slug: str, id: str) -> Response: return Response('Some response')