[Django] Westagram Flow

그냥·2022년 6월 16일
0

django

목록 보기
7/20

1. Django Design Pattern

.
├── 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

2. Flow

1) 초기세팅

  • .gitignore 파일에 my_settings.py 환경변수 관리 파일 추가
  • pip freeze > requirements.py
  • settings.py 파일 설정 점검
  • urls.py 파일 설정 점검

2) Modeling

  • unique 속성 추가
  • max_length 속성 추가
  • created_at, updated_at column
  • Class 단수 | table - 복수

3) 회원가입

  • Input Validation
    - validate_email

    • validate_password
  • 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()를 사용하는 것이 좋다.


4) 로그인

  • 로그인 기능:
    로그인 시 유효성 검사를 이메일, 비밀번호를 따로 진행할 수도 있지만, 동시에 진행할 경우 더 간결한 코드를 만들 수 있다.
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)
  • Key Error
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에 접근하는 두 가지 방법

  1. data['email'] : 이 경우에 matching되는 key값이 없는 경우에는 파이썬이 error를 raise한다. 그렇기 때문에 except KeyError로 빠지게 되고 아래와 같은 if문 코드는 필요가 없게 된다.
  2. data.get('email', None) : matching되는 key 값이 없는 경우에 default로 None을 반환한다. None 외에 다른 것으로 반환하게 할 수도 있다. 따로 에러가 발생하지 않으므로 key를 잘못 입력하여도 다음 코드가 실행된다.
  • except
    except만 사용해서 Error를 핸들링 하는 경우는 피해야한다. 그 이유는 파이썬에서 발생시키는 모든 에러에 대해서 except문으로 빠지게 된다. 그렇기 때문에 디버깅하기 어려워 진다.
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 ..    

0개의 댓글

관련 채용 정보