클래스 뷰 

  • 코드를 재사용하고 뷰를 체계적으로 구성할 수 있다.
  • def 메소드( ) : 형태를 가진다.
  • url 설정시 함수명 뒤에 as_view()를 사용한다.

 

https://www.django-rest-framework.org/tutorial/3-class-based-views/

from rest_framework.views import APIView
from drf_yasg.utils import swagger_auto_schema

# 함수 articleAPI 변형
class ArticleList(APIView):
    def get(self, request, format=None):
        articles = Articles.objects.all()
        serialize = ArticleSerialize(articles, many=True)
        return Response(serialize.data)

    # 스웨거에서도 편집이 가능
    @swagger_auto_schema(request_body=ArticleSerialize)
    def post(self, request, format=None):
        serialize = ArticleSerialize(data = request.data)
        if serialize.is_valid():
            serialize.save()
            return Response(serialize.data, status=status.HTTP_201_CREATED)
        else:
            print(serialize.errors)
            return Response(serialize.errors, status=status.HTTP_400_BAD_REQUEST)
        

class ArticleDetail(APIView):
    def get(self, request, article_id, format=None):
        article = get_object_or_404(Articles, id=article_id)
        serialize = ArticleSerialize(article)
        return Response(serialize.data)

    def put(self, request, article_id, format=None):
        article = get_object_or_404(Articles, id=article_id)
        serialize = ArticleSerialize(article, data = request.data)
        if serialize.is_valid():
            serialize.save()
            return Response(serialize.data)
        return Response(serialize.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, article_id, format=None):
        article = get_object_or_404(Articles, id=article_id)
        article.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

 

 

app - urls.py

# 수정
urlpatterns = [
	# 클래스형을 사용할 때 as_view()를 사용
	path('', views.ArticleList.as_view(), name='index'),
	path('<int:article_id>/', views.ArticleDetail.as_view(), name='article_view'),
]

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

[DRF] 05. 기본 JWT 토큰  (0) 2023.04.24
[DRF] 04.5 Fetch API, CORS 에러  (0) 2023.04.24
[DRF] 03. postman-1, swagger  (0) 2023.04.24
[DRF] 02. @api_view  (0) 2023.04.24
[DRF] 01. 시리얼라이즈  (0) 2023.04.24

postman 활용하기

  • postman 사용시 500번 에러가 발생할 때 슬래시 ( / ) 가 빠지지 않았는지 확인하자.

 

새로고침 : send 클릭

 

 

 

 

 

 

 

 

 

Environments 등록하기

나중에 도메인으로 변경할 때 편리하다.

 

 

 

 

 

 

swagger

api를 알아서 만들어 줌

 

drf-yasg

https://drf-yasg.readthedocs.io/en/latest/readme.html#usage

 

drf-yasg - Yet another Swagger generator — drf-yasg 1.20.1.dev31+gd9700db documentation

Since the schema does not usually change during the lifetime of the django process, there is out of the box support for caching the schema view in-memory, with some sane defaults: caching is enabled by the cache_page decorator, using the default Django cac

drf-yasg.readthedocs.io

pip install drf-yasg
pip freeze > requirements.txt

 

settings.py

# 추가하기

INSTALLED_APPS = [
   'drf_yasg',
]

 

urls.py

from django.urls import re_path
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi


schema_view = get_schema_view(
   openapi.Info(
      title="Snippets API",
      default_version='v1',
      description="Test description",
      terms_of_service="https://www.google.com/policies/terms/",
      contact=openapi.Contact(email="contact@snippets.local"),
      license=openapi.License(name="BSD License"),
   ),
   public=True,
   permission_classes=[permissions.AllowAny],
)


urlpatterns = [
   re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
   re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
   re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]

http://127.0.0.1:8000/swagger/ 로 접속하기

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

[DRF] 04.5 Fetch API, CORS 에러  (0) 2023.04.24
[DRF] 04. 클래스 뷰(CBV)  (0) 2023.04.24
[DRF] 02. @api_view  (0) 2023.04.24
[DRF] 01. 시리얼라이즈  (0) 2023.04.24
11. Django gitignore, 시크릿 키  (0) 2023.04.24

새로운 데이터 만들기

※반드시 문자열을 큰따옴표( " )로 감쌀것

 

 

게시글 보기, 생성

from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from articles.models import Articles
from articles.serializers import ArticleSerialize

@api_view(['GET', 'POST'])
def articleAPI(request):
    if request.method =='GET':
        articles = Articles.objects.all()
        serialize = ArticleSerialize(articles, many=True)
        return Response(serialize.data)
    elif request.method =='POST':
        print(request.data['title'])
        serialize = ArticleSerialize(data = request.data)
        if serialize.is_valid():
            serialize.save()
            return Response(serialize.data, status=status.HTTP_201_CREATED)
        else:
            print(serialize.errors)
            return Response(serialize.errors, status=status.HTTP_400_BAD_REQUEST)

 

 

 

게시글 상세보기, 수정, 삭제

 

app - urls.py 

# 추가
urlpatterns = [
    path('<int:article_id>', views.articleDetailAPI, name='article_view'),
]

 

app - views.py

@api_view(['GET', 'PUT', 'DELETE'])
def articleDetailAPI(request, article_id):
    if request.method == 'GET':
        article = get_object_or_404(Articles, id=article_id)
        serialize = ArticleSerialize(article)
        return Response(serialize.data)
    elif request.method == 'PUT':
        article = get_object_or_404(Articles, id=article_id)
        serialize = ArticleSerialize(article, data = request.data)
        if serialize.is_valid():
            serialize.save()
            return Response(serialize.data)
    elif request.method == 'DELETE':
        article = get_object_or_404(Articles, id=article_id)
        article.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

 

 

 

 

+) origin main으로 push 할 때

에러 :  error: src refspec main does not match any

해결 : git push origin master 

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

[DRF] 04. 클래스 뷰(CBV)  (0) 2023.04.24
[DRF] 03. postman-1, swagger  (0) 2023.04.24
[DRF] 01. 시리얼라이즈  (0) 2023.04.24
11. Django gitignore, 시크릿 키  (0) 2023.04.24
10. Django 폼  (0) 2023.04.24

기본 세팅

 

https://www.django-rest-framework.org/

 

Home - Django REST framework

 

www.django-rest-framework.org

 

# 가상환경에 설치된 목록 확인
pip list
# 설치
pip install django
pip install djangorestframework
pip install django-dotenv
pip freeze > requirements.txt
django-admin startproject drf_week2 .

 

 

 

 

시리얼라이즈

  • 파이썬 객체나 queryset 객체 등을 JSON, XML 형태로 변환하는 것
  • 반대로 JSON 형태를 DB 인스턴스로 변환하는 것은 디시리얼라이즈라고 한다.

JSON 이란?

    Javascript 객체 문법으로 구조화된 데이터를 표현하기 위한 문자 기반의 표준 포맷

     딕셔너리처럼 Key와 Value 값을 가짐

     *parse란? 데이터 해석. deserialization을 포괄 (ex. 압축해제, 코드 컴파일, 브라우저가 html 해석)

 

 

 

 

 (app-models.py)

from django.db import models

class Articles(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(blank=True, null=True)
    crated_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    #admin 페이지에서 게시글 제목으로 나오게 하기
    def __str__(self):
    	return str(self.title)

 *urls.py, (app)admin.py, (app)urls.py 등의 설정 생략

 

 

(app - views.py)

from rest_framework.response import Response

def articleAPI(response):
    return Response('연결되었습니다.')

 

 

(app - serializers.py 생성)

# field 타이핑 에러 :
#("Creating a ModelSerializer without either the 'fields' attribute or 
#the 'exclude' attribute has been deprecated since 3.3.0, and is now disallowed. 
#Add an explicit fields = '__all__' to the StockSerializer serializer.",)

from articles.models import Articles
from rest_framework import serializers

class ArticleSerialize(serializers.ModelSerializer):
    class Meta:
        model = Articles
        # field 아님. 오타 주의
        fields = '__all__'

 

 

 

 

 

시리얼라이즈 사용X  vs  사용O

from rest_framework.response import Response
from rest_framework.decorators import api_view
from articles.models import Articles
from articles.serializers import ArticleSerialize

#브라우저블 API
@api_view(['GET', 'POST'])
def articleAPI(request):
    articles = Articles.objects.all()
    article = articles[0]
    article_data = {
        'title' : article.title,
        'content' : article.content,
    }
    return Response(article_data)
    

#위와 아래 같은 코드


@api_view(['GET', 'POST'])
def articleAPI(request):
    articles = Articles.objects.all()
    # 여러개의 article을 가져올 때 many =True
    serialize = ArticleSerialize(articles, many=True)
    return Response(serialize.data)

+) 데코레이터 : https://winterakoon.tistory.com/80

 

 

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

[DRF] 03. postman-1, swagger  (0) 2023.04.24
[DRF] 02. @api_view  (0) 2023.04.24
11. Django gitignore, 시크릿 키  (0) 2023.04.24
10. Django 폼  (0) 2023.04.24
[DRF] 00.이론  (0) 2023.04.18

git ignore

 

https://www.toptal.com/developers/gitignore

 

gitignore.io

Create useful .gitignore files for your project

www.toptal.com

 

 

 

위와 같이 입력 후 vs code에서 .gitignore를 생성하여 검색 결과를 붙여넣기

+) gitignore에  venv를 입력하면 git에 push 할 때 가상환경은 무시한다.

 

 

 

 

settings.py

# 추가하기
INSTALLED_APPS = [
    'rest_framework',
]


# 변경하기
LANGUAGE_CODE = 'ko-kr'

TIME_ZONE = 'Asia/Seoul'

 

 

 

 

SECRET_KEY

 

 

.env 파일 생성

SECRET_KEY = 'settings.py에 있던 시크릿키를 가져옴'

settings.py 

import os

SECRET_KEY = os.environ.get('SECRET_KEY')

manage.py

import dotenv

if __name__ == '__main__':
    dotenv.read_dotenv()
    main()

 

+) 에러 : a server error occurred. please contact the administrator

# manage.py 괄호 빠트림
dotenv.read_dotenv

 

 

.gitignore

# 상단에 추가하기
.env

 

 

+) 시크릿 키 재생성

python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())'

 재생성된 시크릿키를 .env 파일에 붙여넣기

 

 

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

[DRF] 02. @api_view  (0) 2023.04.24
[DRF] 01. 시리얼라이즈  (0) 2023.04.24
10. Django 폼  (0) 2023.04.24
[DRF] 00.이론  (0) 2023.04.18
09. Django 템플릿 상속  (0) 2023.04.17

+ Recent posts