Source code for nanohttp.exceptions

import ujson
import traceback

from .contexts import context
from .configuration import settings


[docs]class HTTPStatus(Exception): status = None def __init__(self, status=None): if status is not None: self.status = status super().__init__(self.status) def render(self): stack_trace = traceback.format_exc() if context.response_content_type == 'application/json': return ujson.encode( dict( stackTrace=stack_trace) if settings.debug else dict() ) else: context.response_encoding = 'utf-8' context.response_content_type = 'text/plain' return stack_trace if settings.debug else ''
[docs]class HTTPKnownStatus(HTTPStatus): def __init__(self, status_text=None): code, text = self.status.split(' ', 1) super().__init__(f'{code} {status_text or text}')
[docs]class HTTPBadRequest(HTTPKnownStatus): status = '400 Bad Request'
[docs]class HTTPUnauthorized(HTTPKnownStatus): status = '401 Unauthorized'
[docs]class HTTPForbidden(HTTPKnownStatus): status = '403 Forbidden'
[docs]class HTTPNotFound(HTTPKnownStatus): status = '404 Not Found'
[docs]class HTTPMethodNotAllowed(HTTPKnownStatus): status = '405 Method Not Allowed'
[docs]class HTTPConflict(HTTPKnownStatus): status = '409 Conflict'
[docs]class HTTPGone(HTTPKnownStatus): status = '410 Gone'
[docs]class HTTPPreconditionFailed(HTTPKnownStatus): status = '412 Precondition Failed'
[docs]class HTTPRedirect(HTTPKnownStatus): """ This is an abstract class for all redirects. """ def __init__(self, location, *args, **kw): context.response_headers.add_header('Location', location) super().__init__(*args, **kw)
[docs]class HTTPMovedPermanently(HTTPRedirect): status = '301 Moved Permanently'
[docs]class HTTPFound(HTTPRedirect): status = '302 Found'
[docs]class HTTPNotModified(HTTPKnownStatus): status = '304 Not Modified'
[docs]class HTTPInternalServerError(HTTPKnownStatus): status = '500 Internal Server Error'
[docs]class HTTPBadGatewayError(HTTPKnownStatus): status = '502 Bad Gateway'
[docs]class HTTPSuccess(HTTPKnownStatus): status = '200 OK'
[docs]class HTTPCreated(HTTPSuccess): status = '201 Created'
[docs]class HTTPAccepted(HTTPSuccess): status = '202 Accepted'
[docs]class HTTPNonAuthoritativeInformation(HTTPSuccess): status = '203 Non-Authoritative Information'
[docs]class HTTPNoContent(HTTPSuccess): status = '204 No Content'
[docs]class HTTPResetContent(HTTPSuccess): status = '205 Reset Content'
[docs]class HTTPPartialContent(HTTPSuccess): status = '206 Partial Content'