.
├── README.md
├── project
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings/
│ │ ├── base.py
│ │ ├── staging.py
│ │ ├── production.py
│ │ └── local.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
├── my_settings.py
├── requirements/
│ ├── requirements.txt
│ └── requirements-dev.txt
│
├── users
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
└── utils
Input Validation
- validate_email
Email, Password Validation - match vs compile
emailregex = '^[a-zA-Z0-9+-.]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$'
password_regex = "^(?=.[A-Za-z])(?=.\d)(?=.[!%#?&])[A-Za-z\d!%*#?&]{8,}$"
정규표현식을 사용할 경우, 자주 사용되는 경우가 아니라면 compile() 해서 사용하지 않고, match()를 사용하는 것이 좋다.
def post(self, request):
data = json.loads(request.body)
if not User.objects.filter(email = data["email"], password = data["password"]).exists():
return JsonResponse({'message' : 'INVALID_USER'}, status=401)
return JsonResponse({'message' : 'LOGIN SUCCESS'}, status=200)
class SignInView(View):
def post(self, request):
try:
data = json.loads(request.body)
email = data["email"]
password = data["password"]
if not (password and email):
return JsonResponse({'message' : 'KEY_ERROR'}, status=400)
if not User.objects.filter(password=password, email=email):
return JsonResponse({'message' : 'INVALID_USER'}, status=401)
return JsonResponse({'message' : 'SUCCESS'}, status=200)
except KeyError:
return JsonResponse({'message' : 'KEY_ERROR'}, status=400)
Dictionary에 접근하는 두 가지 방법
- data['email'] : 이 경우에 matching되는 key값이 없는 경우에는 파이썬이 error를 raise한다. 그렇기 때문에 except KeyError로 빠지게 되고 아래와 같은 if문 코드는 필요가 없게 된다.
- data.get('email', None) : matching되는 key 값이 없는 경우에 default로 None을 반환한다. None 외에 다른 것으로 반환하게 할 수도 있다. 따로 에러가 발생하지 않으므로 key를 잘못 입력하여도 다음 코드가 실행된다.
try:
..
..
except :
..
import logging
logger = logging.getLogger()
try:
except Exception as e:
logger.error(f"error_message :: {e})
return JesonResponse({"message" : ...})
결론적으로 try, except문을 사용해서 error를 핸들링하는 경우 아래와 같이 에러를 명확하게 잡아줘야 한다.
try:
except KeyError:
return ..
except User.DoesNotExsit:
return ..