본문 바로가기

Backend/Python

[DRF] Django Rest Framework (1-1)

반응형

기능 구현

Member CRUD

Login 기능 - 이메일, 비밀번호 검증

Api문서 자동화 - drf_yasg이용

 

gitHub : https://github.com/DerekYook/MunDeuk_py

 

GitHub - DerekYook/MunDeuk_py: MunDenk ver.python

MunDenk ver.python. Contribute to DerekYook/MunDeuk_py development by creating an account on GitHub.

github.com

 

 

웹페이지는 template를 이용해 form으로 데이터를 주고 받는 식으로 작성했다.

 

현재 프로젝트 디렉토리 구조

projectName/
├── env/
├── projectName/
|   ├── __init__.py
|   ├── settings.py
|   ├── urls.py
|   ├── wsgi.py
|   ├── asgi.py
|   └── appname/
|       ├── migrations/
|       ├── __init__.py
|       ├── admin.py
|       ├── apps.py
|       ├── form.py
│       ├── models.py
│       ├── serializers.py
│       ├── tests.py
│       ├── urls.py
│       └── views.py
├── templates/
|   ├── admin.html
|   ├── index.html
|   ├── login.html
|   ├── signup.html
|   └── error/
│       └── noaccount.html
├── __init__.py
├── db.sqlite3
└── manage.py

 

 

models.py

from django.db import models


# Create your models here.
class MemberInfo(models.Model):
    class MemberAuth(models.TextChoices):
        # Enum_val = 'db_val', 'display_val'
        USER = 'USER', 'User'
        ADMIN = 'ADMIN', 'Admin'

    class MemberState(models.TextChoices):
        ACTIVE = 'A', 'Active'
        INACTIVE = 'I', 'Inactive'
        BANNED = 'B', 'Banned'

    nickName = models.CharField(max_length=100)
    email = models.EmailField(default='default@example.com')
    password = models.CharField(max_length=100)
    memberAuth = models.CharField(max_length=100, choices=MemberAuth.choices, default=MemberAuth.USER)
    memberState = models.CharField(max_length=1, choices=MemberState.choices, default=MemberState.ACTIVE)

    def to_dic(self):
        return {
            "nickName": self.nickName,
            "email": self.email,
            "password": self.password,
            "memberAuth": self.memberAuth,
            "memberState": self.memberState
        }

 

serializers.py

from django.contrib.auth.models import Group, User
from rest_framework import serializers
from .models import MemberInfo


class MemberSerializer(serializers.ModelSerializer):
    class Meta:
        model = MemberInfo
        fields = ['id', 'nickName', 'email', 'password']


class VerifyMember(serializers.ModelSerializer):
    class Meta:
        model = MemberInfo
        fields = ['email', 'password']


class MembersList(serializers.ModelSerializer):

    class Meta:
        model = MemberInfo
        fields = ['id', 'nickName', 'email', 'memberAuth', 'memberState']

 

views.py

from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from .forms import MemberForm

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import MemberInfo
from .serializers import MemberSerializer, VerifyMember, MembersList
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi


# Create your views here.


def index(request):
    return render(request, 'index.html')


@swagger_auto_schema(
    method='get',
    operation_description="Render the signup page",
    responses={
        200: openapi.Response('Signup page rendered'),
        404: 'Not Found'
    }
)
@csrf_exempt
@api_view(['GET'])
def member_signup(request):
    return render(request, 'signup.html')


@swagger_auto_schema(
    method='post',
    request_body=MemberSerializer,
    responses={
        201: openapi.Response('Created', MemberSerializer),
        400: 'Bad Request'
    }
)
@api_view(['POST'])
def member_signup_ajax(request):
    if request.method == 'POST':
        serializer = MemberSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors)


@swagger_auto_schema(
    method='get',
    operation_description="Render the login page",
    responses={
        200: openapi.Response('Login page rendered'),
        404: 'Not Found'
    }
)
@csrf_exempt
@api_view(['GET'])
def member_login(request):
    return render(request, 'login.html')


@swagger_auto_schema(
    method='post',
    request_body=MemberSerializer,
    responses={
        200: openapi.Response('Ok', MemberSerializer),
        400: 'Bad Request',
        401: 'Unauthorized'
    }
)
@api_view(['POST'])
def member_login_ajax(request):
    if request.method == 'POST':
        serializer = VerifyMember(data=request.data)

        if serializer.is_valid():
            email = serializer.validated_data.get('email')
            password = serializer.validated_data.get('password')
            try:
                member = MemberInfo.objects.get(email=email, password=password)
                # 사용자 인증에 성공하면 사용자 데이터를 반환합니다
                return Response(MemberSerializer(member).data, status=status.HTTP_200_OK)
            except MemberInfo.DoesNotExist:
                # 사용자 인증에 실패하면 401 Unauthorized 응답을 반환합니다
                return Response({"error": "Invalid email or password"}, status=status.HTTP_401_UNAUTHORIZED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@swagger_auto_schema(
    method='get',
    operation_description="Render the memberList page",
    responses={
        200: openapi.Response('Login page rendered'),
        404: 'Not Found'
    }
)
@csrf_exempt
@api_view(['GET'])
def members_list(request):
    if request.method == 'GET':
        members = MemberInfo.objects.all()
        serializer = MembersList(members, many=True)
    return render(request, 'admin.html', {'members': serializer.data})


@csrf_exempt
@api_view(['POST'])
def members_update(request):
    if request.method == 'POST':
        for member_data in request.data:
            try:
                member = MemberInfo.objects.get(id=member_data['id'])
                member.memberAuth = member_data['memberAuth']
                member.memberState = member_data['memberState']
                member.save()
            except MemberInfo.DoesNotExist:
                return Response({"error": "Member not found"}, status=status.HTTP_404_NOT_FOUND)
        return Response({"success": "Members updated successfully"}, status=status.HTTP_200_OK)
    return Response({"error": "Invalid request"}, status=status.HTTP_400_BAD_REQUEST)

 

반응형

'Backend > Python' 카테고리의 다른 글

[drf] JWT인증 추가  (0) 2024.07.16
[DRF] Django Rest Framework (1-2)  (0) 2024.07.12
[DRF] Django Rest Framework (1)  (0) 2024.07.09
[DRF] Django Rest Framework (0)  (0) 2024.07.09
[Django] 게시판, 관리자, Superuser  (0) 2024.04.01