Django 동적 URL 패턴 로직 추가- 5

2023. 2. 26. 15:47·Develop/Django
728x90
SMALL

1개의 함수 안에 많은 if문을 하게 되면 코드 가독성 부분과 확장성에 제한이 있다.

그래서 함수안의 데이터를 분리시켜 로직을 짜게 되면 코드 관리가 편해진다.

 

1) 월의 집합을 dict로 생성한다.

monthly_case = {"january": "Django is fun!",
                "february": "Coding for at least 1 hour every day!",
                "march": "Hard Coding is hard",
                "april": "Let's split the if statement",
                "may": "Create new function",
                "june": "Code management made easy",
                "july": "Django is fun!",
                "august": "Coding for at least 1 hour every day!",
                "september": "Hard Coding is hard",
                "october": "Let's split the if statement",
                "november": "Create new function",
                "december": "Code management made easy"
                }

 

2) 기존 함수를 고쳐본다.

# if 구문
def monthly_challenge(request, month):
    response = monthly_case.get(month)
    if response:
        return HttpResponse(response)
    return HttpResponseNotFound("Not month")
    
# try 구문
def monthly_challenge(request, month):
    try:
    	response = monthly_case[month]
        return HttpResponse(response)
    except:
    	return HttpResponseNotFound("Not month")

 

728x90
SMALL
저작자표시 비영리 (새창열림)

'Develop > Django' 카테고리의 다른 글

Django URL reverse / URL name - 7  (0) 2023.02.27
Django 리다이렉트(Redirect) - 6  (0) 2023.02.26
Django 경로 변환(타입 추가) - 4  (0) 2023.02.26
Django 동적 URL 패턴(Dynamic Path Segments) - 3  (0) 2023.02.25
Django View & URL 다뤄보기 - 2  (0) 2023.02.25
'Develop/Django' 카테고리의 다른 글
  • Django URL reverse / URL name - 7
  • Django 리다이렉트(Redirect) - 6
  • Django 경로 변환(타입 추가) - 4
  • Django 동적 URL 패턴(Dynamic Path Segments) - 3
동석해요
동석해요
공부하고 싶은게 많은, 사소한 IT 지식들 공유
    250x250
  • 동석해요
    개발로 자기계발
    동석해요
  • 전체
    오늘
    어제
    • 분류 전체보기 (226)
      • Develop (126)
        • 기초지식 (12)
        • FastAPI (102)
        • Django (11)
      • Database & Data (62)
        • 기초지식 (16)
        • MySQL (29)
        • PostgreSQL (8)
        • 데이터 분석 (9)
      • 인공지능 (11)
        • PyTorch (9)
      • Cloud (8)
        • AWS (4)
        • GCP (2)
      • 버그처리 (14)
      • 회고 & 일상 (5)
  • 인기 글

  • 최근 글

  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
동석해요
Django 동적 URL 패턴 로직 추가- 5
상단으로

티스토리툴바