[PYTHON] How to use Decorator in Django and how to make it

background

I'm making a webapp with Django, but when I read the document on the Admin page, it seems that the following two codes can be replaced.

admin.py


from django.contrib import admin
from .models import Author

#No decorator
  class AuthorAdmin(admin.ModelAdmin):
    pass
  admin.site.register(Author, AuthorAdmin)

#With decorator
  @admin.register(Author)
  class AuthorAdmin(admin.ModelAdmin):
    pass

Well, I don't feel grateful if there is only one, but if there are dozens of admin.site.register (sth, sthAdmin) lined up, it's not easy on the eyes, so it's better to substitute this. I mean.

So what is a decorator! I thought, so I will investigate and summarize it within the range that I somehow understood.

The original article is here. It seems to be a topic of a system that can be understood and used only after the experience value has risen a little more. At least for me.

If you summarize only what you know first,

--If you define it on function or class, it will give you some effect. --For example, you can limit the execution of view to only logged-in users. --If you log or define a class, you can execute it without permission.

Well, it seems convenient, so I'll remember one by one each time it appears. Let's start.

Decorators are functions

Ignore the annoying concept of @ for now and compare the case with and without the Decorator.

example1.py



#With Decorator
  @login_required
  def my_view(request):
   return HttpResponse()


#No decorator
  def my_view(request):
   return HttpResponse

  my_view = login_required(my_view)

example2.py


#With Decorator
  @require_http_method(['GET','POST'])
  def my_view(request):
   return HttpResponse()


#No decorator
  def my_view(request):
   return HttpResponse()
  
  my_view = require_http_method(['GET'],['POST'])(my_view)
 

Without Decorator parameters

As you can see from the explanation so far, the decorator is just a function, it seems to take the function that follows as a parameter and take over the role. (Interpreted with this, there is no problem at present)

For example, when my_view (request) is called, it seems that it is actually equivalent to login_required (my_view) (request) being called.

One thing to note here is that Decorator is a type of design pattern when coding, not unique to python or Django.

So if you have some knowledge of python, you can make a decorator yourself. So, let's take a look at how to make a decorator little by little.

Introduction

Create an identity decorator. It doesn't do anything, it just takes a function and returns it. It's just the role of view in django.

example3.py


def identity(a_view):
  return a_view

In this case, the decorator above does the same job as my_view (request). Well, I'm still not sure. ..

Step 2

I decided to make a decorator that actually does some work. Let's try to make a decorator that logs the number of times the view is called.

example4.py


def log(a_view):
  def _wrapped_view(request, *args, **kwargs):
    logger.log('My view is called')
    return a_view(request, *args, **kwargs)
  return _wrapped_view

What I made here

――Take some kind of log --Return the view received by parametar as it is

What a simple decorator. The procedure to be executed is as follows.

I don't know if it really makes sense, but it seems that I can log with this for the time being.

Next, add a feature to this decorator to see if the user trying to run wrapped_view is logged in.

example5.py


def login_required(a_view):
  def _wrapped_view(request, *args, **kwargs):
    if request.user.is_authenticated():
      return a_view(request, *args, **kwargs)
    return HttpResponseForbiden()
  return _wrapped_view

I'm not sure, but I wonder if my memory and comprehension are poor. ..

Recommended Posts

How to use Decorator in Django and how to make it
How to use is and == in Python
How to install Cascade detector and how to use it
How to make a container name a subdomain and make it accessible in Docker
How to use the decorator
[Python] [Django] How to use ChoiceField and how to add options
How to define Decorator and Decomaker in one function
How to use bootstrap in Django generic class view
How to use classes in Theano
How to reflect CSS in Django
How to use .bash_profile and .bashrc
How to install and use Graphviz
How to use Mysql in python
How to use ChemSpider in Python
How to use PubChem in Python
Try to make it using GUI and PyQt in Python
How to use Laravel-like ORM / query builder Orator in Django
How to use pyenv and pyenv-virtualenv in your own way
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
How to create and use static / dynamic libraries in C
Comparison of how to use higher-order functions in Python 2 and 3
How to use calculated columns in CASTable
[Introduction to Python] How to use class in Python?
processing to use notMNIST data in Python (and tried to classify it)
How to install OpenCV on Cloud9 and run it in Python
How to install and use pandas_datareader [Python]
How to delete expired sessions in Django
How to use Google Test in C
How to use functions in separate files Perl and Python versions
How to use Anaconda interpreter in PyCharm
python: How to use locals () and globals ()
How to use __slots__ in Python class
How to use Python zip and enumerate
How to do Server-Sent Events in Django
How to use regular expressions in Python
How to convert DateTimeField format in Django
How to use Map in Android ViewPager
How to use pandas Timestamp and date_range
How to return the data contained in django model in json format and map it on leaflet
How to use the C library in Python
How to use lists, tuples, dictionaries, and sets
Introducing Sinatra-style frameworks and how to use them
How to generate permutations in Python and C ++
How to implement Rails helper-like functionality in Django
How to use Python Image Library in python3 series
How to reflect ImageField in Django + Docker (pillow)
How to run some script regularly in Django
Summary of how to use MNIST in Python
How to use tkinter with python in pyenv
[Python] How to use hash function and tuple.
How to create a Rest Api in Django
How to write async and await in Vue.js
How to make Python Interpreter changes in Pycharm
How to plot autocorrelation and partial autocorrelation in python
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use virtualenv
How to use Seaboan
How to use image-match
How to use Pandas 2