Understanding decorators that work as wrappers

Now, we will make a few changes to the code in the toys/views.py file to provide support for the OPTIONS verb in our RESTful Web Service. Specifically, we will take advantage of a decorator provided by the Django REST framework.

We will use the @api_view decorator that is declared in the rest_framework.decorators module. We will apply this decorator to our function-based views: toys_list and toys_detail.

The @api_view decorator allows us to specify which are the HTTP verbs that the function to which it is applied can process. If the request that has been routed to the view function has an HTTP verb that isn't included in the string list specified as the http_method_names argument for the @api_view decorator, the default behavior returns a response with an HTTP 405 Method Not Allowed status code.

This way, we make sure that whenever the RESTful Web Service receives an HTTP verb that isn't considered within our function views, we won't generate an unexpected and undesired error in Django. The decorator generates the appropriate response for the unsupported HTTP verbs or methods. In addition, by reading the declaration of our function views, we can easily understand which HTTP verbs are handled by the function.

It is very important to understand what happens under the hood whenever we use the @api_view decorator. This decorator is a wrapper that converts a function-based view into a subclass of the rest_framework.views.APIView class. This class is the base class for all the views in the Django REST framework.

We will work with class-based views in the forthcoming examples and we will have the same benefits we have analyzed for the function-based views that use the decorator.

In addition, the decorator uses the string list we specify with the supported HTTP verbs to build the response for a request with the OPTIONS HTTP verb. The automatically generated response includes the supported method, and the parser and the render capabilities. In other words, the response includes the format that the function is capable of understanding and the format that the function can generate for the response.

As previously explained, the current version of our RESTful Web Service is only capable of rendering JSON as its output. The usage of the decorator makes sure that we always receive an instance of the rest_framework.request.Request class in the request argument when Django calls our view function. In addition, the decorator handles the ParserError exceptions when our function views access the request.data attribute and there are parsing problems.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.121.131