RESTful and HTTP APIs in Pyramid Transcripts
Chapter: A nearly RESTful service
Lecture: Concept: JSON renderer for custom types
Login or
purchase this course
to watch this video and the rest of the course contents.
0:01
So as we've seen, if the thing we want to return back to the renderer to the json renderer, somehow somewhere inside of its object graph has a thing
0:11
that the json serializer, the json module can't deal with, all bets are off, thing crash, right, like it just says nope, we cannot help you.
0:19
But, it's also not a big problem to fix. So, if the object knows how to serialize itself, or if you're willing to write a function
0:29
that will take the object from what it is into a dictionary or something like that, something the json module can deal with, then you're golden, right;
0:36
so in our case, I put this method on the car because it seems like a great place to keep it as we add field
0:42
we just got to update this method, which is slightly error prone, but not super hard.
0:46
And then, in our __init__ the entry point for the main app when we're starting it up,
0:51
we're going to call, we are going to write and call this function register renderers.
0:55
And here instead of taking the default one, the default json renderer, we can actually create either a new one
1:02
or replace the one that is configured at startup by default. So here we're going to create a json renderer
1:07
using the json type built in the pyramid renderers, notice I am setting indent=4 that basically tells, passes through to the json module
1:17
which tells it to do pretty printing and indenting 4, I guess if I wanted Firefox to agree exactly on the pretty printing
1:23
I could put the number 2 there, but the fact that I am setting indent to something means that it's going to do pretty printing,
1:30
and then we can also add this adapter, say given a car object, you can call this lambda function and it takes two parameters,
1:35
the first one is the thing we care about the car and then we'll just call the to_dict, or whatever function it is
1:40
that transforms the car instance into something serializable. And then we're golden, and then we just have to make sure we register that with pyramid
1:46
so we say config, add renderer, and we pass the json renderer and we can pick either json which will replace the built in one,
1:54
or in this case, we're going to say pretty json, so if you want to call this function and have like pretty printed json,
2:00
you can put that, just make sure if you're really depending on that, you could also add the adapter to the built in json one.
2:06
And that's all there is to it, now we can get a lot more mileage out of the built in json renderer.
2:10
But, by looking at this, we also see how we can add new types csv renderers, image renderers, xml renderers, and so on,
2:17
so that is what we are going to look at next.