훈훈훈

파이썬(Django) : 회원가입, 로그인 Simple API 구현 본문

파이썬/Django

파이썬(Django) : 회원가입, 로그인 Simple API 구현

훈훈훈 2020. 2. 10. 09:59

Django(장고)를 이용해 회원가입과 로그인 기능을 가진 API를 구현해보았다.

 

# 디렉터리 구조

아래 명령어를 사용하여 프로젝트(mysite)와 앱(account)을 생성하였다.

 > django-admin startproject mysite .

 > python manage.py startapp account 

 

# models.py

from django.db import models

class Account(models.Model):
    name       = models.CharField(max_length = 50)
    password   = models.CharField(max_length= 200)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'accounts'

models.py 파일은 데이터베이스 테이블을 만들고 그 안의 필드들을 생성 및 수정할 수 있는 역할을 한다.

따라서 현재 로그인 및 회원가입 기능 구현이 목적이기 떄문에 name(id), password 그리고 생성 시간 및 수정 시간 컬럼을 만들었다. 마지막으로 테이블명을 'accounts' 로 명시하였다.

  ** Class Name : 단수, Table Name : 복수로 작성하는 것이 일반적이다.

 

# view.py

view.py 은 models.py에서 만든 DB 테이블의 데이터를 처리하는 로직을 만들 수 있다.

import json

from .models      import Account

from django.views import View
from django.http  import HttpResponse, JsonResponse

먼저 임포트한 모듈을 살펴보면 Http 통신으로 Json 파일 데이터를 주고 받기 위해 Json 모듈을 임포트했다.

그리고 models.py에 있는 Account 클래스 등을 임포트 하였다.

class AccountView(View):
    def post(self, request):
        data = json.loads(request.body)
        Account.objects.create(
            name=data['name'], 
            password=data['password']
        )

        return HttpResponse(status=200)
    
    def get(self, request):
        Account_data = Account.objects.values()
        return JsonResponse({'accounts' : list(Account_data)}, status=200)

models.py 에서 만든 테이 데이터를 주고 받고 저장하기 위해 AccountView 클래스를 생성하였다.

post 메서드로 요청 받을 시 name 과 password를 저장하는 기능을 구현하였고 get 메서드로 요청 받을 시 account 테이블에 저장된 리스트를 출력하도록 하였다.

class SignView(View):
    def post(self, request):
        data = json.loads(request.body)

        try:
            if Account.objects.filter(name = data['name']).exists():
                user = Account.objects.get(name=data['name'])

                if user.password == data['password']:
                    return HttpResponse(status=200)
                return HttpResponse(status=401)
            return HttpResponse(status=400)
        
        except KeyError:
            return JsonResponse({'message' : "INVALID_KEYS"}, status=400)

그 다음으로 간단하게 로그인 하는 로직을 구현하였다.

Http request로 받은 json 파일을 읽은 후 테이블에 저장된 name 과 password를 비교하여 DB내에 저장되어 있는 사용자면 200 OK를 반환하고 로그인 실패 시 400 에러를 반환하도록 작성하였다.

 

# urls.py

마지막으로 URL 경로를 담당하는 urls.py 파일을 작성하였다.

  - mysite.urls.py

from django.urls import path, include

urlpatterns = [
    path('account', include('account.urls')),
]

mysite 디렉터리에 있는 urls.py 에 'account' path를 추가하여 account 경로로 request를 보낼 수 있게 하였다.

 

  - account.urls.py

from django.urls import path
from .views      import AccountView, SignView

urlpatterns = [
    path('', AccountView.as_view()),
    path('/sign-up', AccountView.as_view()),
    path('/sign-in', SignView.as_view()),
]

마지막으로 account 경로에 urls.py를 생성 후 post, get 메서드로 요청 받을 시 해당 기능을 하는 클래스를 요청할 수 있게 작성하였다.

 

urls.py 파일을 mysite 경로애 한꺼번에 작성하지 않고 분리하여 작성한 이유는 URLconf 모듈을 계층적으로 구성하는 것이 변경 및 확장에 용이하기 때문이다.

 

# 결과

''brew install httpie" 명령어로 httpie를 설치 후 http -v [Server Ip:port]/경로로 Request 요청을 보내 정상적으로 코드가 작성이 되었는지 테스트 하였다.

 

- 회원 가입

name = test, password = 1234 로 /accoun/sign-up 경로로 Request 요청 시 정상적으로 200 OK가 출력되는 것을 볼 수 있다.

- 회원 조회

/account 경로로 GET 메서드로 요청 시 테이블에 저장된 데이터가 출력되는 것을 볼 수 있다.

- 로그인

 => 성공 

account 테이블에 저장된 test/1234 계정으로 정상 접속되는 것을 확인 할 수 있다.

 => 실패

password를 틀리게 입력 시 401 에러를 반환하는 것을 확인할 수 있다.

Comments