10.URL Dispatcher와 정규표현식

최대 1 분 소요

URL Dispatcher

  • project/settings.py에서 최상위 URLConf 모듈을 지정

  • HTTP 요청이 들어오면 urlpatterns상에 매핑 리스트를 순차적으로 훑으며 URL 매칭시도

정규표현식

거의 모든 프로그래밍 언어에서 지원 문자열의 패턴, 규칙, Rule을 정의하는 방법

path()와 re_path()의 등장

django 1.x에서의 Django.conf.urls.url() 사용이 2가지로 분리

  • django.urls.re_path()
    • django.conf.urls.url()과 동일
  • django.urls.path()
    • 기본 지원되는 Path converters를 통해 정규표현식 기입이 간소화 -> 만능은 아님
    • 자주 사용하는 패턴을 Converter로 등록하면 재활용면에서 편리함
from django.conf.urls import url
from django.urls import path, re_path 

urlpattern = [
    # 장고 1.x에서의 코드
    url(r'^articles/?P<year>[0-9]{4}/$', views.year_archive),

    # 다음과 같이 같소화 가능
    path('articles/<int:year>/', views.year_archive),

    # re_path 스타일
    re_path(r'articles/(?P<year>[0-9]{4})/$', views.year_archive),
]

정규표현식 패턴 예시

  • 1자리 숫자 -> [0123456789] 혹은 [0-9] 혹은 r”[\d]” 혹은 r”\d”
  • 2자리 숫자 -> [0123456789][0123456789] 혹은 [0-9][0-9] 혹은 \d\d
  • 3자리 숫자 -> r”\d\d\d” 혹은 r”\d{3}”
  • 2자리~4자리 숫자 -> r”\d{2,4}”
  • 휴대폰 번호 -> r”010[1-9]\d{7}”
  • 알파벳 소문자 1글자 -> [abcdefghijklmnopqrstuvwxyz] 혹은 [a-z]
  • 알파벳 대문자 1글자 -> [ABCDEFGHIJKLMNOPQRSTUVWXYZ] 혹은 [A-Z]

새로운 장고 앱 생성할때, 추천 작업

  • 앱/urls.py
# 앱/urls.py
from django.urls import path
from 앱이름 import views

app_name = '앱 이름'

urlpatterns = [

]
  • 프로젝트/urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('앱이름/', include('앱이름.urls')),
]

댓글남기기