Table of Contents
- Why doesn't RequestHandler.request.arguments interpret JSON POST bodies?
- How do I make a custom 404 page?
- Why don't tornado.escape.json_encode and json_decode pass unknown keyword arguments to the underlying implementation? OR Why don't json_encode and json_decode use [some faster json library] when available?
Why doesn't RequestHandler.request.arguments
interpret JSON POST bodies?
request.arguments and the methods that work with it (get_argument
,
get_arguments
, decode_argument
) are designed around the limitations
and peculiarities of the x-www-form-encoded
format (technically a
multimap but typically used as a map, underspecified character
encodings, etc). If you weren't saddled with that format to begin
with, why try to fit your relatively expressive json data into its
constraints?
Just do something like this, and then use self.json_args.get("foo")
instead of self.get_argument("foo")
:
def prepare(self):
if self.request.headers.get("Content-Type") == "application/json":
self.json_args = json_decode(self.request.body)
How do I make a custom 404 page?
Just add a rule at the end of your handlers list that matches everything:
(r'.*', My404Handler)
In My404Handler
, use self.set_status(404)
and then render a page as usual. For non-404 errors, you can override write_error
in your handler class.
Why don't tornado.escape.json_encode and json_decode pass unknown keyword arguments to the underlying implementation? OR Why don't json_encode and json_decode use [some faster json library] when available?
These two common requests are mutually exclusive - one ties json_encode more closely to a specific implementation, and the other requires the underlying implementation be swappable. In both cases I feel like the best approach is to leave tornado.escape.json_encode as a lowest-common-denominator json implementation that is available on all platforms where tornado runs. If you want more features that are provided by a specific json library, you should probably just import and use that library directly instead of using the tornado.escape version.