[Django] Handling HTTP Requests

Jin·2021년 9월 12일
0

django

목록 보기
7/14
post-thumbnail

Handling HTTP Requests

  1. Django shortcut functions
  2. View decorators

1. Django shortcuts function

  • django.shortcuts 패키지는 개발에 도움 될 수 있는 여러 함수와 클래스를 제공
  • shortcuts function 종류
    • render()
    • redirect()
    • get_object_or_404()
    • get_list_or_404()

get_object_or_404()

  • 모델 manager objects에서 get()을 호출했을때, 해당 객체가 없으면 DoesNotExist 예외 대신 Http 404를 raise
  • get() 메서드에 경우 조건에 맞는 데이터가 없을 경우에 에러를 발생 시킴
    • 코드 실행 단계에서 발생한 에러에 대해서 브라우저는 http status code 500으로 인식
  • 상황에 따라 적절한 예외처리를 하고 클라이언트에게 올바른 에러를 전달하는 것 또한 개발의 중요한 요소 중 하나
def detail(request, pk):
    article = get_object_or_404(Article,pk=pk)
    context = {
    	'article' : article,
        }

Django View decorators

  • Django는 다양한 HTTP 기능을 지원하기 위해 view에 적용할 수 있는 여러 데코레이터를 제공
  • 어떤 함수에 기능을 추가 하고 싶을 때, 해당 함수를 수정하지 않고 기능을 연장해주는 함수

Allowed HTTP methods

  • 요청 메서드에 따라 view 함수에 대한 엑세스를 제한
  • 요청이 조건을 충족시키지 못하면 HttpResponseNotAllowed을 return(405 Method Not Allowed)
  • require_http_methods(), require_POST(), require_safe(), require_GET()

require_http_methods()

  • view 함수가 특정한 method 요청에 대해서만 허용하도록 하는 데코레이터
from django.views.decorators.http import require_http_methods

  @require_http_method(['GET','POST'])
  def my_view(request):
  	pass
  

require_POST()

  • view 함수가 POST method 요청만 승인하도록 하는 데코레이터
from django.views.decorators.http import require_POST

@require_POST
def delete(request,PK):
    #if로 확인하던것이 필요 없어짐
    article = get_object_or_404(Article, pk=pk)
    article.delete()
    return redirect('aritlces:index')
    
# POST가 아닐때는 사용자가 405 error를 받음 

만약 require_GET() 을 사용하고 싶다면 require_GET() 보다는 require_safe()를 사용하는것이 더 좋다.
Why?

Web servers should automatically strip the content of responses to HEAD requests while leaving the headers unchanged, so you may handle HEAD requests exactly like GET requests in your views. Since some software, such as link checkers, rely on HEAD requests, you might prefer using require_safe instead of require_GET.

https://docs.djangoproject.com/en/3.2/topics/http/decorators/

profile
내가 다시 볼려고 작성하는 블로그. 아직 열심히 공부중입니다 잘못된 내용이 있으면 댓글로 지적 부탁드립니다.

0개의 댓글