--- title: TastyPie Note 1 date: 2016-05-10 17:00:00 tags: - tastypie - django --- ### Flow Through The Request/Response Cycle Tastypie can be thought of as a set of class-based view that provide the API functionality. All routing/middleware/response-handling aspectss are the same as a typical Django app. Where the differs is in the view itself. Walking through what a GET request to a list endpoint looks like: - The `Resource.urls` are checked by Django's url resolvers. - On a match for the list view, `Resource.wrap_view('dispatch_list')` is called. `wrap_view` provides basic error handling & allows for returning serilized errors. - Because dispatch_list was passed to `wrap_view`, `Resource.dispatch_list` is called next. This is a thin wrapper around `Resource.dispatch`. - `dispatch` does a bunch of havy lifting. It ensures: - the requested HTTP method is in `allowed_methos` (`method_check`). - the class has a method that can handle the request(`get_list`) - the user is authenticated(`is_authenticated`) - the user has no exceeded their throttle(`throttle_check`). At this point, `dispatch` actually calls the requested method (`get_list`). - `get_list` does the actual work of API. It does: - A fetch of the available objects via `Resource.obj_get_list`. In the case of `ModelResource`, this builds the ORM filters to apply (`ModelResource.build_filters`). It then gets the `QuerySet` via `ModelResource.get_object_list` (which performs `Resource.authorized_read_list` to possibly limit the set the user can work with) and applies the built filters to it. - It then sorts the objects based on user input (`ModelResource.apply_sorting`). - Then it paginates the results using the supplied `Paginator` & pulls out the data to be serialized. - The objects in the page have `full_dehydrate` applied to each of them, causing Tastypie to traslate the raw object data into the fields the endpoint supports. - Finally, it calls `Resource.create_response`. - `create_response` is a shortcut method that: - Determines the desired response format (`Resource.determine_format`). - Serializes the data given to it in the proper format. - Returns a Django `HttpResponse` (200 OK) with the serialized data. - We bubble back up the call stack to `dispatch`. The last thing `dispatch` does is potentially store that a request occured for future throttling (`Resource.log_throttled_access`) then either returns the `HttpResponse` or wraps whatever data came back in a response (so Django doesn't freak out).