반응형
pr이 merge되면 로컬 main에서
git pull origin main
으로 main을 업데이트 한 후 회원가입 기능을 개발할 브랜치를 만들어서 이동후 작업한다
git checkout -b feature/signup
회원가입 뷰 정의(views.py)
- 사용자 정보는 이름, 이메일, 비밀번호, 연락처(휴대폰), 그 외 개인정보를 포함한다.
- 이메일이나 패스워드가 전달되지 않을 경우, {"message": "KEY_ERROR"}, status code 400 을 반환
import json
# 데이터를 주고받을때 제이슨 타입의 데이터를 주고받는데 파이썬에서 그 데이터를 사용하기 위해 파이썬에서 쓸 수 있는 형태로 바꿔주어야 한다. 그때 사용하는 패키지이다.
from django.http import JsonResponse
# render나 httpresponse 대신 JsonResponse를 응답객체로 사용할 거라서
# 원래 있던 from django.shortcuts import render를 지우고 넣는다
from django.views import View
# 장고에서 정의해둔 뷰클래스를 상속받아서 뷰를 정의하기 위해 import
from users.models import User
# 우리가 users.models에 정의해둔 User클래스를 사용하기 위해 import
class SignUpView(View): # 뷰의 이름은 모델클래스와 구분하기 위해 뒤에 View를 붙여준다. user데이터를 다룰거기 때문에 user+view로 만든다
def post(self, request): # 회원가입(데이터 저장)은 POST메서드로 요청이 온다
try:
data = json.loads(request.body)
# 요청으로 오는 제이슨 데이터의 body의 json타입 데이터를 파이썬에서 사용할 수 있게 딕셔너리 형태로 바꿔주는 작업
# request는 클라이언트가 주는 리쿼스트 객체->클래스로 만든 인스턴스라서 .을 통해 속성값에 접근 가능하다. request.body에는 클라이언트가 보낸 바디가 들어가있다.
# jason.load로 http request메세지의 바디를 딕셔너리 형태로 변환 후에 data에 할당해서 사용한다.
name = data['name']
email = data['email']
password = data['password']
mobile_number = data['mobile_number']
# 키에러를 먼저 잡기 위해서 하나씩 할당을 먼저 해주었다.
except KeyError:
return JsonResponse({"message": "KEY_ERROR"}, status=400)
# 응답할 때는 다시 파이썬 딕셔너리 형태의 데이터를 json형태로 바꿔서 응답해준다. 첫번째 인자에 딕셔너리를 넣어준다.
>그밖의 키에러처리
더보기
# if문으로 처리하는 방법
class SignUpView(View):
def post(self, request):
data = json.loads(request.body)
name = data.get("name", None)
email = data.get("email", None)
if not (password and email):
return JsonResponse({"message":"KeyError"}, status=400)
# validate_email, validate_password 함수를 분리한 경우.
class SignUpView(View):
def post(self, request):
data = json.loads(request.body)
name = data['name']
email = data['email']
if password == None or email == None:
return JsonResponse({"message":"KeyError"}, status=400)
- 이메일에는 @와 .이 필수로 포함되어야 합니다. 해당 조건이 만족되지 않은 경우 적절한 에러를 반환해주세요. 이 과정을 Email Validation이라고 합니다. 정규표현식을 활용해주세요.
- 비밀번호는 8자리 이상, 문자, 숫자, 특수문자의 복합이어야 합니다. 해당 조건이 만족되지 않은 경우, 적절한 에러를 반환해주세요. 이 과정을 Password Validation이라고 합니다. 정규표현식을 활용해주세요.
import json, re # 정규식을 사용하기 위해 re import
from django.http import JsonResponse
from django.views import View
from users.models import User
class SignUpView(View):
def post(self, request):
try:
data = json.loads(request.body)
name = data['name']
email = data['email']
password = data['password']
mobile_number = data['mobile_number']
REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
REGEX_PASSWORD = '^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$'
if not re.match(REGEX_EMAIL, email):
return JsonResponse({'message':'EMAIL_VALIDATION_FALSE'}, status=400)
if not re.match(REGEX_PASSWORD, password):
return JsonResponse({'message':'PASSWORD_VALIDATION_FALSE'}, status=400)
# 모두 요청이 잘못된 경우라서 400을 반환했다
except KeyError:
return JsonResponse({"message": "KEY_ERROR"}, status=400)
- 회원가입시 서로 다른 사람이 같은 이메일을 사용하지 않으므로 기존에 존재하는 자료와 중복되면 안됩니다. 적절한 에러를 반환해주세요.
- 회원가입이 성공하면 {"message": "SUCCESS"}, status code 201을 반환합니다.
import json, re
from django.http import JsonResponse
from django.views import View
from users.models import User
class SignUpView(View):
def post(self, request):
try:
data = json.loads(request.body)
name = data['name']
email = data['email']
password = data['password']
mobile_number = data['mobile_number']
REGEX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
REGEX_PASSWORD = '^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$'
if not re.match(REGEX_EMAIL, email):
return JsonResponse({'message':'EMAIL_VALIDATION_FALSE'}, status=400)
if not re.match(REGEX_PASSWORD, password):
return JsonResponse({'message':'PASSWORD_VALIDATION_FALSE'}, status=400)
if User.objects.filter(email=email).exists(): # 같은 이메일이 이미 데이터베이스에 존재하면 에러 반환
return JsonResponse({'message': 'EMAIL_MUST_BE_UNIQUE'}, status=400)
User.objects.create( # 모든 예외처리를 다 통과하면 회원데이터를 저장하는 작업을 한다
name = name,
email = email,
password = password,
mobile_number = mobile_number
)
return JsonResponse({'message': 'SUCCESS'}, status=201)
# 그리고 성공메세지를 보낸다 post메서드에 따라 데이터가 잘 생성/수정되었다는 코드 201을 보낸다
except KeyError:
return JsonResponse({"message": "KEY_ERROR"}, status=400)
URLconf정의
어떤 데이터에 접근하는지 명확히 알 수 있는 엔드포인트를 생성한다.
# westagram_1.urls.py
from django.urls import include, path
urlpatterns = [
path('user', include('users.urls'))
]
# 들어온 요청의 url에 user가 있으면 그 뒷부분을 users.urls로 보낸다
# users.urls.py(이 파일은 직접 만들어야 한다)
from django.urls import path
from users.views import SignUpView
urlpatterns = [
path("/signup", SignUpView.as_view())
]
# 메인 url에서 넘어온 부분이 /signup을 포함하면 SignUpView를 실행한다
user가 회원가입 할때 오는 요청이라
/user/signup으로 지정했다.
테스트
더보기
httpie로 테스트
1. 이메일 조건 안맞을때
http -v POST http://127.0.0.1:8000/user/signup name=' 인스타' email='a@' password='pw' mobile_number='01011111234'
POST /user/signup HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 95
Content-Type: application/json
Host: 127.0.0.1:8000
User-Agent: HTTPie/3.2.1
{
"email": "a@",
"mobile_number": "01011111234",
"name": "인스타",
"password": "pw"
}
HTTP/1.1 400 Bad Request
Content-Length: 37
Content-Type: application/json
Cross-Origin-Opener-Policy: same-origin
Date: Sat, 16 Jul 2022 12:53:54 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.9.12
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
{
"message": "EMAIL_VALIDATION_FALSE"
}
2. 비밀번호 조건 안맞을때
http -v POST http://127.0.0.1:8000/user/signup name='인스타' email='a@gmail.com' password='user1pw' mobile_number='01011111234'
POST /user/signup HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 109
Content-Type: application/json
Host: 127.0.0.1:8000
User-Agent: HTTPie/3.2.1
{
"email": "a@gmail.com",
"mobile_number": "01011111234",
"name": "인스타",
"password": "user1pw"
}
HTTP/1.1 400 Bad Request
Content-Length: 40
Content-Type: application/json
Cross-Origin-Opener-Policy: same-origin
Date: Sat, 16 Jul 2022 12:56:10 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.9.12
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
{
"message": "PASSWORD_VALIDATION_FALSE"
}
3. 성공
http -v POST http://127.0.0.1:8000/user/signup name=' 인스타' email='a@gmail.com' password='user1pw!' mobile_number='01011111234'
POST /user/signup HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 110
Content-Type: application/json
Host: 127.0.0.1:8000
User-Agent: HTTPie/3.2.1
{
"email": "a@gmail.com",
"mobile_number": "01011111234",
"name": "인스타",
"password": "user1pw!"
}
HTTP/1.1 201 Created
Content-Length: 22
Content-Type: application/json
Cross-Origin-Opener-Policy: same-origin
Date: Sat, 16 Jul 2022 12:54:37 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.9.12
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
{
"message": "SUCCESS"
}
서버 메세지
Bad Request: /user/signup
[16/Jul/2022 12:53:54] "POST /user/signup HTTP/1.1" 400 37
[16/Jul/2022 12:54:37] "POST /user/signup HTTP/1.1" 201 22
Bad Request: /user/signup
[16/Jul/2022 12:56:10] "POST /user/signup HTTP/1.1" 400 40
# 이메일실패-성공-비번실패 순서로 진행했다
데이터베이스
mysql> table users;
+----+-----------+-------------+----------+---------------+----------------------------+----------------------------+
| id | name | email | password | mobile_number | created_at | updated_at |
+----+-----------+-------------+----------+---------------+----------------------------+----------------------------+
| 1 | 인스타 | a@gmail.com | user1pw! | 01011111234 | 2022-07-16 12:54:37.578555 | 2022-07-16 12:54:37.579532 |
+----+-----------+-------------+----------+---------------+----------------------------+----------------------------+
1 row in set (0.00 sec)
잘 작동하는지 확인 후 github에 push->pr
반응형
'wecode' 카테고리의 다른 글
[Mission 5] 회원가입 비밀번호 암호화 적용 (0) | 2022.07.17 |
---|---|
[Mission 4] 로그인 기능 구현 (0) | 2022.07.16 |
[Mission 2] 모델링 (0) | 2022.07.16 |
Code Kata | Week2 - Day5 (0) | 2022.07.15 |
Code Kata | Week2 - Day4 (0) | 2022.07.14 |