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