회원가입 기능을 구현하기 위해,
class SignUpView(View):
def post(self, request):
data = json.loads(request.body)
User.objects.create(
name = data['name'],
email = data['email'],
password = data['password'],
phone_number = data['phone_number'],
age = data['age'],
gender = data['gender'],
birth_date = data['birth_date']
)
return JsonResponse({"MESSAGE": "SUCCESS"}, status=201)
json 형태로 데이터를 request, response 하도록
위와 같이 코드를 작성하였다.
하지만, 위 기능으로 회원가입을 하다보면 몇가지 문제점이 발생한다.
일단, 전달 받은 데이터 중에 KeyError
가 발생하는 경우를 생각하여,
class SignUpView(View):
def post(self, request):
data = json.loads(request.body)
try:
User.objects.create(
name = data['name'],
email = data['email'],
password = data['password'],
phone_number = data['phone_number'],
age = data['age'],
gender = data['gender'],
birth_date = data['birth_date']
)
return JsonResponse({"MESSAGE": "SUCCESS"}, status=201)
except KeyError:
return JsonResponse({"MESSAGE":"KEY_ERROR"},status=400)
try
, except
로 KeyError
발생 시에, 해당하는 메시지와 status코드를 response하도록 처리하였다.
그리고 email
과 phone_number
는 unique(중복되는 값이 없음!)한 특성을 가지므로 아래와 같이,
class SignUpView(View):
def post(self, request):
data = json.loads(request.body)
try:
if User.objects.filter(email=data['email']).exists():
return JsonResponse({"MESSAGE":"ALREADY_EMAIL_EXSISTS"}, status=400)
if User.objects.filter(phone_number=data['phone_number']).exists():
return JsonResponse({"MESSAGE":"ALREADY_PHONE_NUMBER_EXSISTS"},
status=400)
User.objects.create(
name = data['name'],
email = data['email'],
password = data['password'],
phone_number = data['phone_number'],
age = data['age'],
gender = data['gender'],
birth_date = data['birth_date']
)
return JsonResponse({"MESSAGE": "SUCCESS"}, status=201)
except KeyError:
return JsonResponse({"MESSAGE":"KEY_ERROR"},status=400)
DB에 접근하여, 각각 email
과 phone_number
에 해당하는 객체가 존재할 경우(exists()
메서드 사용)를 구분하여 response를 하도록 작성하였다.
Validations?
validation이란 어떤 데이터의 값이 유효한지, 타당한지 확인하는 것을 의미한다.
즉, 위 경우에서 email과 password는 특정한 형태나 조건을 가지고 있다. 그렇기 때문에 규격에 맞는 형식으로 데이터를 입력해야 하기 때문에 꼭 필요한 작업이다.
email
에는 @
, .
이 필수로 포함되어야 하기 때문에,
정규표현식을 이용하여 유효성 검사를 하도록 하였다.
일단 regexr 홈페이지에 접속하여, 정규표현식을 작성하고 테스트하였다.
^[a-zA-Z0-9-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-_]+\.*[a-zA-Z0-9-_]+$
작성한 정규표현식을 활용하기 위해,
re
모듈을 불러와서 표현식을 만족하지 않으면 True
가 반환되도록 만들었다.
import re
def email_validation(email):
p = re.compile('^[a-zA-Z0-9-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-_]+\.*[a-zA-Z0-9-_]+$')
return not p.match(email)
만약
'abc123@gmail.com'과 같이 유효하면False
'abcabc@gmail', 'abc123.com'과 같이 유효하지 않으면True
가 반환된다.
password
또한 8글자 길이 이상의 문자, 숫자, 특수문자의 복합으로 이루어지도록 정규표현식을 작성하고, 만족하지 않는다면 True
가 반환되는 함수를 만들었다.
def password_validation(password):
p = re.compile('^[A-Za-z\d$@$()^!%*#?&].{8,}$')
return not p.match(password)
그 후에, SignUpView
메소드에 그에 맞는 메시지와 status를 response하도록 작성하면 validations가 완료된다.
최종
import json, re
from django.http import JsonResponse
from django.views import View
from users.models import User
def email_validation(email):
p = re.compile('^[a-zA-Z0-9-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-_]+\.*[a-zA-Z0-9-_]+$')
return not p.match(email)
def password_validation(password):
p = re.compile('^[A-Za-z\d$@$()^!%*#?&].{8,}$')
return not p.match(password)
class SignUpView(View):
def post(self, request):
data = json.loads(request.body)
try:
email = data['email']
password = data['password']
phone_number = data['phone_number']
if email_validation(email):
return JsonResponse({"MESSAGE":"INVALID_EMAIL"}, status=400)
if password_validation(password):
return JsonResponse({"MESSAGE":"INVALID_PASSWORD"}, status=400)
if User.objects.filter(email=email).exists():
return JsonResponse({"MESSAGE":"ALREADY_EMAIL_EXSISTS"}, status=400)
if User.objects.filter(phone_number=phone_number).exists():
return JsonResponse({"MESSAGE":"ALREADY_PHONE_NUMBER_EXSISTS"},
status=400)
User.objects.create(
name = data['name'],
email = data['email'],
password = data['password'],
phone_number = data['phone_number'],
age = data['age'],
gender = data['gender'],
birth_date = data['birth_date']
)
return JsonResponse({"MESSAGE": "SUCCESS"}, status=201)
except KeyError:
return JsonResponse({"MESSAGE":"KEY_ERROR"},status=400)