The blog of FirstprayerOn The Way To Be A Data Scientist
I'm developing a Mini Course about Web Development. Check it out!
Using Python Decorators in Web Development
Decorator is a very useful technique for dynamically alter the functionality of a function, method or class. It also allows us to write reusable code in a very elegant way. In this post I’ll discuss the usage of decorators in web development.
1. What is decorator?
There’s a brilliant post about this. To summarize the content from this post:
A decorator is a function that takes a function object as an argument, and returns a function object as a return value.
An example:
The way to use a decorator is:
Or, use the syntax suger provided by Python, just:
2. An example
Now let’s see how to use decorators to make our code more elegant, and more reusable. The example is based on Django
Suppose we have a web controller(or view):
Now, suppose we want to add several new controlers, such as:
It’s obvious that the first several steps of these controllers are the same. How can we write reusable code for this? We can do this by writing decorators! Here’s how:
We write a decorator writers_required:
And change the update_article controller to:
Similarly, we can implement other decorators:
Now the update_article controller becomes:
See?! The function is extremely elegant now. For other similar controllers:
From this very simple example, we can see that decorator is really a great tool for reusing codes.
Some decorators above are already provided by Django, so it seems unnecessary to implement it again. However, these decorators, as well as the idea of using decorators, are not restricted in Django, nor in Python only. When we’re using other python-based web framework, or even web frameworks in other languages, we can always consider using decorators(even the language itself doesn’t support such syntax).