Django : Westagram #3 회원가입 정규식 모듈화

Jinsung·2021년 11월 25일
0

회원가입 정규식 모듈화

기존 전체 코드에 정규식에 관한 조건문이나 변수를 validation.py파일을 생성하여 모듈화 진행

class SignUpView(View):
    def post(self, request):
        try:
            data         = json.loads(request.body)
            name         = data["name"]
            email        = data['email']
            password     = data["password"]
            phone        = data["phone"]
            email_regex  = '^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$'
            passwd_regex = '^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$'

            if User.objects.filter(email=email).exists():
                return JsonResponse({"message" : "EMAIL_ALREADY_EXISTS"}, status=400)

            if not re.match(email_regex, email):
                return JsonResponse({"message": "EMAIL_ERROR"}, status=400)

            if not re.match(passwd_regex, password):
                return JsonResponse({"message": "PASSWORD_ERROR"}, status=400)

            User.objects.create(
                name     = name,
                email    = email,
                passwd   = password,
                phone    = phone
                )
            return JsonResponse({"message": "Success"}, status = 201)
        
        except KeyError:
            return JsonResponse({"message": "KEY_ERROR"}, status=400)

모듈 만들기

touch validation.py 생성 및 전체 코드에서 정규식에 관련된 조건문이나 변수를 가지고 온다.

validation.py

            email_regex  = '^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$'
            passwd_regex = '^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$'
            
            if not re.match(email_regex, email):
                return JsonResponse({"message": "EMAIL_ERROR"}, status=400)

            if not re.match(passwd_regex, password):
                return JsonResponse({"message": "PASSWORD_ERROR"}, status=400)

이메일과 패스워드를 한번에 관리해도 괜찮지만 따로 관리해주게 사후 관리에 좋기때문에 분리한다.

            email_regex  = '^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$'
            if not re.match(email_regex, email):
                return JsonResponse({"message": "EMAIL_ERROR"}, status=400)
                
               passwd_regex = '^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$'
               if not re.match(passwd_regex, password):
                return JsonResponse({"message": "PASSWORD_ERROR"}, status=400)
                

함수를 만들고 각자 필요한 값을 인자로 받는다
return 대신 raise ValidationError로 인스턴스에러를 표시한다.


from django.core.exceptions import ValidationError

def signup_email(email):
    email_regex  = '^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$'
    if not re.match(email_regex, email):
        raise ValidationError("EMAIL_ERROR")

def signup_password(password):
    passwd_regex = '^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$'
    if not re.match(passwd_regex, password):
        raise ValidationError("PASSWORD_ERROR")

모듈 적용

정규식 검사는 모듈에 있는 함수를 불러와 진행하고 에러 처리는 ValidationError를 바라보게 해준다.

from .validation            import signup_password, signup_email
from django.core.exceptions import ValidationError

 def post(self, request):
        try:
            data         = json.loads(request.body)
            name         = data["name"]
            email        = data['email']
            password     = data["password"]
            phone        = data["phone"]
	    
          # validation.py에 있는 함수로 처리
            signup_email(email)
            signup_password(password)

            if User.objects.filter(email=email).exists():
                return JsonResponse({"message" : "EMAIL_ALREADY_EXISTS"}, status=400)
                
             User.objects.create(
                name     = name,
                email    = email,
                password = hashed_password,
                phone    = phone
                )

            return JsonResponse({"message": "Success"}, status = 201)
        
        except KeyError:
            return JsonResponse({"message": "KEY_ERROR"}, status=400)
#에러 처러
        except ValidationError as e:
            return JsonResponse({"message": e.message}, status=400)

0개의 댓글