The AnnotatedHandler class¶
The AnnotatedHandler class subclasses from Tornado's RequestHandler. Subclasses of the AnnotatedHandler are able to - declare path and query params, json body model and the response model in the function signature - validate, type cast and pass in declared params before declared methods are executed
Differences¶
With Tornado, we subclass from the RequestHandler and define the path parameter in the overridden get
method.
We then retrieve query params and json body by using methods like get_query_argument
and parsing the request body.
from tornado.escape import json_decode
from tornado.web import RequestHandler
class TornadoRequestHandler(RequestHandler):
async def get(self, a_path_param):
a_query_param = int(self.get_query_argument("a_query_param"))
a_request_body = json_decode(self.request.body)
self.write(
{
"a_path_param": a_path_param,
"a_query_param": a_query_param,
"a_request_body": a_request_body,
}
)
For subclasses of AnnotatedHandler
, the annotated function arguments are used to parse the incoming request for the required fields, and passed into the functions.
from torn_open import AnnotatedHandler, RequestModel, ResponseModel
class ARequestBody(RequestModel):
a_body_param: bool
class AResponseModel(ResponseModel):
a_path_param: str
a_query_param: int
request_body: ARequestBody
class TornOpenAnnotatedHandler(AnnotatedHandler):
async def get(
self, a_path_param: str, a_query_param: int, a_request_body: ARequestBody
) -> AResponseModel:
return AResponseModel(
a_path_param=a_path_param,
a_query_param=a_query_param,
a_request_body=a_request_body,
)
Parameters¶
The AnnotatedHandler
uses a set of rules to determine where the parameter should be parsed from
Path parameters¶
- If an argument appears in the url rule for the handler, it is treated as a path parameter
- 1 or more path parameters can be declared in the url rule.
- If the url rule includes a path parameter that is not in the function signature, an error may be raised at runtime.
Query parameters¶
If an argument does not appear in the url rule for the handler, and its type annotation is not a subclass of torn_open.RequestModel
, it is treated as a query parameter.
JSON body¶
- If an argument does not appear in the url rule for the handler, and its type annotation is a subclass of
torn_open.RequestModel
, then it is parsed as a JSON object. - Only 1 argument in a function can be annotated as a subclass of
torn_open.RequestModel
.