Wecode #12 TIL Django - Project 따라하기#4

황인용·2019년 12월 25일
0

wecode TIL

목록 보기
12/12

pango user기능에 try|except문 수정하기

user.views.py의 UserView클래스와 AuthView클래스를 try except문으로 수정

HTTP Status Code

http status code란, server와 client간에 HTTP통신을 하면서 제데로 통신이 되었는지, 안되었다면 무엇이 문제인지 상태를 알려주는 code이다.
http status code는 총 3자리 숫자로 크게는 5개로 나눠진다.

  • 1XX (조건부 응답)
  • 2xx (성공)
  • 3xx (리다이렉션 완료)
  • 4xx (요청 오류)
  • 5xx (서버 오류)
    ( * xx는 두자리한자리 숫자)

자주 사용하는 HTTP Status Code

200 OK
가장 자주 보게 되야하는 status code.
문제 없이 통신이 완료 되었음을 알려주는 code.

301 Moved Permanently
해당 URL이 다른 주소로 변경 되었음을 알려주는 code.

HTTP/1.1 301 Moved Permanently
Location: http://www.example.org/index.asp

400 Bad Request
해당 요청이 잘못된 요청일대 보내는 code.
주로 요청에 포함된 input 값들이 잘못된 값들이 보내졌을때 사용되는 code.
예를 들어, 전화번호를 보내야 되는데 text가 보내졌을때 등등.
TypeError 또는 except KeyError(키에러)

401 Unauthorized
이 요청은 인증이 필요하다. 서버는 로그인이 필요한 페이지에 대해 이 요청을 제공할 수 있다. 상태 코드 이름이 권한 없음(Unauthorized)으로 되어 있지만 실제 뜻은 인증 안됨(Unauthenticated)에 더 가깝다

403 Forbidden
유저가 해당 요청에 대한 권한이 없음을 알리는 code.
예를 들어, 예를 들어, 오직 과금을 한 유저만 볼 수 있는 데이터를 요청 했을때

404 Not Found
요청된 URL이 존재 하지 않다는 code.

http -v google.com/no-such-uri

GET /no-such-uri HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: google.com
User-Agent: HTTPie/0.9.3

HTTP/1.1 404 Not Found
Content-Length: 1572
Content-Type: text/html; charset=UTF-8
Date: Mon, 20 Aug 2018 08:46:48 GMT
Referrer-Policy: no-referrer

500 Internal Server Error
서버내에서 에러가 났을 때 알려주는 code.
API개발을 하는 백앤드 개발자들이 가장 싫어하는 코드. 즉 백엔드쪽 점검필요

같은 code이여도 그 내용이 다름으로 http 통신 테스트를 통해 여러가지의 경우를 찾아보고 try except문으로 상황에 맞는 code를 로직을 구성하고 frontend와 상황을 주고 받아야한다.

1. user/views.py

여러가지 상황을 test하여 로직을 구성한 결과 다음과 같은 views.py에 try except문을 구성하였다.

import jwt
import json
import bcrypt

from django.views   import View
from django.http    import JsonResponse
from django.db      import IntegrityError
from wiso.settings  import SECRET_KEY

from .models        import Users

class UserView(View):
    def post(self, request):
        data = json.loads(request.body)
        try:
            Users(
                name            = data['name'],
                email           = data['email'],
                password        = data['password'],
            ).save()

            return JsonResponse({'message':'SUCCESS'}, status=200)
        except KeyError:#키에러
            return JsonResponse({'message':'INVALID_KEYS'}, status=400)
        except IntegrityError:#유니크한 데이터 필드에 중복값을 입력시
            return JsonResponse({'message':'EXCEPTED_DATA'}, status=401)


class AuthView(View):
    def post(self, request):
        data = json.loads(request.body)
        try:
            user = Users.objects.get(email = data['email'])
            if data['password'] == user.password:
                return JsonResponse({'message':'오오 인증됨!'}, status=200)
            else:
                return JsonResponse({'message':'INVALID_KEYS'}, status=401)
        except KeyError: #키에러
            return JsonResponse({'message':'INVALID_KEYS'}, status = 400)
        except Users.DoesNotExist: #유저가 존재하지 않을 경우
            return JsonResponse({'message':'INVALID_USER'}, status = 400)

2. run server | httpie

2-1 http status = 200
[server]

$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
December 25, 2019 - 16:43:01
Django version 3.0.1, using settings 'wiso.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[25/Dec/2019 16:45:46] "POST /user/auth HTTP/1.1" 200 47

[client]

$ http -v localhost:8000/user/auth name='test' email='test@gmail.com' password='1234'
POST /user/auth HTTP/1.1
Accept: application/json, */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 63
Content-Type: application/json
Host: localhost:8000
User-Agent: HTTPie/0.9.8

{
    "email": "test@gmail.com",
    "name": "test",
    "password": "1234"
}

HTTP/1.1 200 OK
Content-Length: 47
Content-Type: application/json
Date: Wed, 25 Dec 2019 07:45:46 GMT
Server: WSGIServer/0.2 CPython/3.7.5
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

{
    "message": "오오 인증됨!"
}

2-2 http status = 400 KeyError 키에러
[server]

Bad Request: /user/auth
[25/Dec/2019 16:50:03] "POST /user/auth HTTP/1.1" 400 27

[client]

$ http -v localhost:8000/user/auth name='test' email='test@gmail.com' pw='1234'
POST /user/auth HTTP/1.1
Accept: application/json, */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 57
Content-Type: application/json
Host: localhost:8000
User-Agent: HTTPie/0.9.8

{
    "email": "test@gmail.com",
    "name": "test",
    "pw": "1234"
}

HTTP/1.1 400 Bad Request
Content-Length: 27
Content-Type: application/json
Date: Wed, 25 Dec 2019 07:50:03 GMT
Server: WSGIServer/0.2 CPython/3.7.5
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

{
    "message": "INVALID_KEYS"
}

2-3 http statu=400 유저가 존재하지 않는 경우
[server]

Bad Request: /user/auth
[25/Dec/2019 16:53:42] "POST /user/auth HTTP/1.1" 400 27

[client]

$ http -v localhost:8000/user/auth name='pang' email='pang@gmail.com' password='1234'
POST /user/auth HTTP/1.1
Accept: application/json, */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 63
Content-Type: application/json
Host: localhost:8000
User-Agent: HTTPie/0.9.8

{
    "email": "pang@gmail.com",
    "name": "pang",
    "password": "1234"
}

HTTP/1.1 400 Bad Request
Content-Length: 27
Content-Type: application/json
Date: Wed, 25 Dec 2019 07:53:42 GMT
Server: WSGIServer/0.2 CPython/3.7.5
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

{
    "message": "INVALID_USER"
}

2-4 http status = 401 키에러(없는password값)
[server]

Unauthorized: /user/auth
[25/Dec/2019 16:48:26] "POST /user/auth HTTP/1.1" 401 27

[client]

$ http -v localhost:8000/user/auth username='test' email='test@gmail.com' password='12345'
POST /user/auth HTTP/1.1
Accept: application/json, */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 68
Content-Type: application/json
Host: localhost:8000
User-Agent: HTTPie/0.9.8

{
    "email": "test@gmail.com",
    "password": "12345",
    "username": "test"
}

HTTP/1.1 401 Unauthorized
Content-Length: 27
Content-Type: application/json
Date: Wed, 25 Dec 2019 07:48:26 GMT
Server: WSGIServer/0.2 CPython/3.7.5
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

{
    "message": "INVALID_KEYS"
}
profile
dev_pang의 pang.log

0개의 댓글