How do I return HTTP error code without default template in Tornado?

后端 未结 7 2264
情深已故
情深已故 2021-02-01 02:40

I am currently using the following to raise a HTTP bad request:

raise tornado.web.HTTPError(400)

which returns a html output:

&         


        
7条回答
  •  無奈伤痛
    2021-02-01 03:25

    For json error response i use follow template:

    Request handler:

    import json
    from tornado.web import RequestHandler
    from src.lib.errors import HTTPBadRequest
    
    
    class JsonHandler(RequestHandler):
    
        def prepare(self):
            content_type = ''
            if "Content-Type" in self.request.headers:
                content_type = self.request.headers['Content-Type']
    
            if content_type == 'application/json':
                try:
                    self.request.body = json.loads(self.request.body.decode('utf-8'))
                except ValueError:
                    raise HTTPBadRequest
    
        def write_error(self, *args, **kwargs):
            err_cls, err, traceback = kwargs['exc_info']
            self.set_status(err.status_code)
            if err.description:
                self.write_json(err.description)
            self.finish()
    
        def set_default_headers(self):
            self.set_header('Content-Type', 'application/json')
    
        def write_json(self, response):
            self.write(json.dumps(response))
    

    Errors handler:

    from typing import Any
    from tornado import httputil
    
    
    class BaseHTTPError(Exception):
        def __init__(
            self, status_code: int = 500, description=None, *args: Any, **kwargs: Any
        ) -> None:
            if description is None:
                description = {}
            self.status_code = status_code
            self.description = description
            self.args = args
            self.kwargs = kwargs
    
        def __str__(self) -> str:
            message = "HTTP %d: %s" % (
                self.status_code,
                httputil.responses.get(self.status_code, "Unknown"),
            )
            return message
    
    
    class HTTPBadRequest(BaseHTTPError):
        def __init__(self, *args, **kwargs):
            super().__init__(status_code=400, description={"error": "Bad Request"}, *args, **kwargs)
    

提交回复
热议问题