Well, as the name suggest a decorator is an addition to that which already exists. So, with that said, DRF view decorators make it possible to add more functionality to the already existing functionality.
DRF view decorators come in a variety of flavors, from basic @api_view to more complex and even custom ones. We will be looking at what decorators are and how to use them to make your functions more robust.
You will be using decorators when you want to augment functionality. So, to make it easier to remember, just have it as functionality. So, you will use DRF view decorators with functions.
The first thing you will need to do is to import a decorator from:
restframework.decorators
For example, let’s assume you want to use @api_view decorator. You will simply get it into the scope of your script by:
from restframework.decorators import api_view
NB: Notice that you don’t need to import it with the @ symbol.
The next thing is to actually use it. So, this is where the decoration actually happens. So, how do you do this? Simply:
from restframework.decorators import api_view
@api_view()
def your_cool_decorated_function(request):
""" Your function explanation """
As you can see, it is this simple. HOWEVER, one important thing to know about decorating a DRF function based view is that api_view decorator ALWAYS comes first. Then after that, you can have other decorators following suit.
Well, DRF decorators also do accept arguments, and the arguments, for DRF view decorators is a single list!
That is just all about it. The reason for this simplicity is that each DRF decorator is designed in mind to do a specific thing, and do it really good!
Some decorators like api_view decorator have a default argument. So, to override the default, or to add more arguments, simply pass in an argument list, and remember to include the default if you still want to support it.
For example:
from restframework.decorators import api_view
@api_view([‘GET’, ‘POST’])
def your_cool_decorated_function(request):
""" Your function explanation """
Your decorated your_cool_decorated_function now accepts POST request as well as the default GET request.
As you can see, it is not difficult to work with DRF decorators. Simply find the decorator that you want to use and then decorate your functions with it – pun intended.
Well, until the next article.