Python - 장식자(decorator)
2023. 3. 8. 11:17ㆍ개발/토막난 상식
반응형
@decorator_function
def func():
pass
사용자가 편리해지기 위한 것
다른 함수를 감싸고 있는 함수
def decorator(func):
def deco_func():
print("tistory")
func()
return deco_func
def function1():
print("aaaaaaaa")
function1 = decorator(function1)
function1()
# tistory
# aaaaaaaa
def decorator(func):
def deco_func():
print("tistory")
func()
return deco_func
@decorator
def function1():
print("aaaaa")
function1()
# tistory
# aaaaa
FBV 에 decorators 사용법
FBV 는 함수로 작성하기 때문에 기존에 알던 방법과 동일합니다.
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
# 방법 1
@login_required
def post_create(request):
# 생략
return render(request, 'core/index.html')
# 방법 2
def post_create(request):
# 생략
return render(request, 'core/index.html')
post_create = login_required(post_create)
CBV 에 decorators 사용법
첫 번째 방법으로는 as_view 를 이용해서 함수를 만든 다음 함수를 감싸주는 방법
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
class MyTemplateView(TemplateView):
template_name= "core/index.html"
index = MyTemplateView.as_view()
index = login_required(index)
두 번째 방법은 dispatch 함수를 사용하는 방법입니다. 이 함수는 클래스가 새로운 함수를 만들 때마다 항상 실행되는 함수이기 때문에 이 함수를 재정의하며 메소드 데코레이터를 추가해주는 방법
from django.utils.decorators import method_decorator
class MyTemplateView(TemplateView):
template_name= "core/index.html"
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
index = MyTemplateView.as_view()
세 번째 방법, @method_decorator 는 name 값을 지정함으로서 클래스 메소드에 대해서 해당 decorator 를 사용할 수 있다. 원리적으로는 방법 2와 동일하나 가독성을 해칠 염려가 없다.
@method_decorator(login_required, name="dispatch")
class MyTemplateView(TemplateView):
template_name= "core/index.html"
index = MyTemplateView.as_view()
반응형
'개발 > 토막난 상식' 카테고리의 다른 글
URL Reverse (0) | 2023.03.08 |
---|---|
vsc Import not be resolved from source (0) | 2023.03.08 |
함수기반 뷰 (0) | 2023.03.07 |
쿠키 세션 (0) | 2023.03.07 |
협업_마이그레이션 (0) | 2023.03.07 |