def test_http_error_status_must_be_int_or_http_status(): HTTPError(404) HTTPError(HTTPStatus.NOT_FOUND) with pytest.raises(AssertionError) as ctx: HTTPError("404") assert "int or HTTPStatus" in str(ctx.value)
async def validate_course(req, res, params): """Validate a request payload for required Course fields.""" try: # Request body consumption! # Also available: await req.body() data = await req.json() except JSONDecodeError: # HTTP error responses! raise HTTPError(400, detail="Invalid JSON") # NOTE: you're free to integrate a third-party # validation library such as Marshmallow or jsonschema. for field in "name", "teacher": if field not in data: raise HTTPError(400, detail=f"{field} is a required field")
async def get_course(req, res, pk: int): course = storage.get(pk) if course is None: raise HTTPError(404) res.media = course._asdict() # Background tasks! # Will execute after `res` has been sent # (but NOT in a separate thread). @res.background async def mark_course_as_seen(): await analytics.mark_seen(pk)
async def requires_token(req, res, params): """Protects a view behind token-based authorization.""" if req.token is None or not _is_valid(req.token): raise HTTPError(401)
async def before_dispatch(self, req, res): raise HTTPError(401)
async def on_no_match(req, res, exc): raise HTTPError(404)
async def index(req, res): raise HTTPError(status_code)
def test_http_error_str_representation(): assert str(HTTPError(404, detail="foo")) == "404 Not Found"
async def index(req, res): raise HTTPError(403, detail=detail)