개발로 자기계발
728x90

앞서 다뤄본 것은 "Redirect"였다. 여기서 monthly_challenge_by_number 함수의 redirect 구문에 challenges를 지정해서 넣어줬었다. 하지만 이렇게 되면 monthly_challenges 폴더의 urls.py에 url을 변경하게 되면 페이지를 호출할 수 없게 된다.

물론, 함수의 redirect구문을 똑같이 변경해주면 문제가 없다. 하지만 웹 규모가 커지게 되면 오류를 찾기가 힘들 수 있다.

 

ex) monthly_challenges 폴더 URL

challenges => challenge

urlpatterns = [
    path("challenge/", include("challenges.urls"))
]

ex) monthly_challenge_by_number 함수

challenges

def monthly_challenge_by_number(request, month: int):
    monthly_case_key = list(monthly_case.keys())

    if month > len(monthly_case_key):
        return HttpResponseNotFound("Not month")

    response = monthly_case_key[month - 1]
    return HttpResponseRedirect(f"/challenges/{response}")

URL reverse / name

 

1) challenges(앱)의 url에 name을 추가한다.

이름을 사용하여 경로 URL을 구성할 수 있다.

from django.urls import path

from . import views

urlpatterns = [
    path("<int:month>", views.monthly_challenge_by_number),
    path("<str:month>", views.monthly_challenge, name="month-challenge")
]

 

2) view에 reverse를 추가한다.

from django.urls import reverse

def monthly_challenge_by_number(request, month: int):
    monthly_case_key = list(monthly_case.keys())

    if month > len(monthly_case_key):
        return HttpResponseNotFound("Not month")

    response = monthly_case_key[month - 1]
    redirect_path = reverse("month-challenge", args=[response])
    return HttpResponseRedirect(redirect_path)

reverse는 전달받은 인수(name)와 매칭되는 URL을 반환한다.

여기서는,  path("<str:month>", views.monthly_challenge, name="month-challenge") 반환한다.


Reverse 추가 설명

=> view 함수를 사용하여 URL을 역으로 계산하는 것

=> url.py에서 호출할 url name만 알고 있다면 view를 통해 name에 해당되는 url을 찾아 호출할 수 있다.

 

장점

  • URL이 변경이 되어도 자동으로 URL을 추척
  • 개발자가 변경되어도 URL을 하드코딩하지 않아도 된다.
  • 코드 관리, 유지 보수 용이

 

Reverse를 할 수 방법에는 여러 가지가 있다고 한다.

reverse, resolve_url, redirect, {% url %}

 

728x90
SMALL
profile

개발로 자기계발

@김잠봉

틀린부분이나 조언이 있다면 언제든 환영입니다:-)