[Django] View decorators

cdwdeยท2021๋…„ 3์›” 31์ผ
0

Django

๋ชฉ๋ก ๋ณด๊ธฐ
8/13

๐ŸŽˆ django.views.decorators.http

๋ฐ์ฝ”๋ ˆ์ดํ„ฐ๋Š” ์กฐ๊ฑด์ด ์ถฉ์กฑ๋˜์ง€ ์•Š์œผ๋ฉด django.http.HttpResponseNotAllowed ๋ฐ˜ํ™˜

  • require_http_methods(request_method_list): ๋ทฐ๊ฐ€ ํŠน์ • ์š”์ฒญ ๋ฉ”์†Œ๋“œ๋งŒ ํ—ˆ์šฉํ•˜๋„๋ก ์š”๊ตฌ

  • require_GET(): ๋ทฐ๊ฐ€ GET ๋ฉ”์†Œ๋“œ๋งŒ ํ—ˆ์šฉํ•˜๋„๋ก ์š”๊ตฌ

  • require_POST(): ๋ทฐ๊ฐ€ POST ๋ฉ”์†Œ๋“œ๋งŒ ํ—ˆ์šฉํ•˜๋„๋ก ์š”๊ตฌ

  • require_safe(): ๋ทฐ๊ฐ€ GET ๋ฐ HEAD ๋ฉ”์†Œ๋“œ๋งŒ ํ—ˆ์šฉํ•˜๋„๋ก ์š”๊ตฌ


๐ŸŽˆ django.contrib.auth.decorators

  • user_passes_test: ์ง€์ • ํ•จ์ˆ˜๊ฐ€ False๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด login_url๋กœ redirect

  • login_required: ๋กœ๊ทธ์•„์›ƒ ์ƒํ™ฉ์—์„œ login_url๋กœ redirect

  • permission_required: ์ง€์ • ํผ๋ฏธ์…˜์ด ์—†์„ ๋•Œ login_url๋กœ redirect


๐ŸŽˆ django.contrib.admin.views.decorators

  • staff_member_required: staff member๊ฐ€ ์•„๋‹ ๊ฒฝ์šฐ login_url๋กœ ์ด๋™

๐ŸŽˆ 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์— ์‚ฌ์šฉ

  1. 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 = MyTemplate.as_view()
index = login_required(index)

  1. dispatch ํ•จ์ˆ˜ ์‚ฌ์šฉ
  • dispatch๋Š” ํด๋ž˜์Šค๊ฐ€ ์ƒˆ๋กœ์šด ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค ๋•Œ ๋งˆ๋‹ค ํ•ญ์ƒ ์‹คํ–‰๋˜๋Š” ํ•จ์ˆ˜
  • 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 = MyTmeplateView.as_view()
  1. @method_decorator์— name ์ง€์ •ํ•ด ํด๋ž˜์Šค ๋ฉ”์†Œ๋“œ์— ๋Œ€ํ•ด decorator ์‚ฌ์šฉํ•˜๊ธฐ
@method_decorator(login_required, name='dispatch')
class MyTemplateView(TemplateView):
  template_name = 'core/index.html'
  
index = MyTemplateView.as_view()

์ฐธ๊ณ 
https://ssungkang.tistory.com/entry/Django-FBV-%EC%99%80-CBV-%EC%9D%98-decorators-%EC%82%AC%EC%9A%A9%EB%B2%95?category=320582

0๊ฐœ์˜ ๋Œ“๊ธ€