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 |