Django

파이썬 장고 실무 심화 2주차 1_api view, response

끈끈 2023. 4. 19. 16:43

https://sw-ing.tistory.com/85

 

DRF 시작하기

기본 설정 python -m venv venv source venv/Scripts/Activate pip install django pip install djangorestframework pip freeze > requirements.txt >>> pip install -r requirements.txt 프로젝트 시작 django-admin startproject drf_week2 . >>> . 으로 현

sw-ing.tistory.com

https://www.json.org/json-en.html

 

JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language Standard ECMA-262 3rd Edition

www.json.org

 


 

articles > admin.py:

from django.contrib import admin
from articles.models import Article  # articles 앱의 Article 모델

admin.site.register(Article)

 

articles > models.py:

from django.db import models


class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self): # 모델 클래스 객체의 문자열 표현을 리턴
        return str(self.title)

 

self.title

 

 

drf_week2 > urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('articles/', include("articles.urls")),
]

 

articles > urls.py:

from django.urls import path
from articles import views

urlpatterns = [
    path('index/', views.index, name="index"),
]

 

articles > views.py:

from rest_framework.response import Response


def index(request):
    return Response("연결 완료!")

 

https://www.django-rest-framework.org/tutorial/2-requests-and-responses/

 

2 - Requests and responses - Django REST framework

From this point we're going to really start covering the core of REST framework. Let's introduce a couple of essential building blocks. REST framework introduces a Request object that extends the regular HttpRequest, and provides more flexible request pars

www.django-rest-framework.org

 


 

.accepted_renderer not set on Response
>>> you forgot to add the @api_view and the @renderer_classes decorator to your view.

 

/articles/index/

 

 

articles > views.py:

from rest_framework.response import Response
from rest_framework.decorators import api_view


@api_view(['GET'])
def index(request):
    return Response("연결 완료!")

 

api_view란? rest_framework에서 API를 간편하게 사용하게 하기 위한 브라우저블 API로

 

직접 브라우저에서 조작이 가능하게 해주고

 

돌려주는 response 또한 있는데 rest_framework.response

 

/articles/index/ - GET
/articles/index/ - GET, POST

 


 

db의 articles의 데이터 가져오기

 

articles > views.py:

from rest_framework.response import Response
from rest_framework.decorators import api_view
from articles.models import Article


@api_view(['GET'])
def index(request):
    articles = Article.objects.all()
    print(articles) # <QuerySet [<Article: hi>]>
    return Response(articles)

 

Object of type Article is not JSON serializable
>>> Response에 담을 수 있는 값은 string, dictionary, list

 

/articles/index/

 

def index(request):
    articles = Article.objects.all()
    article = articles[0]
    article_data = {
        'title': article.title,
        'content': article.content,
        'created_at': article.created_at,
        'updated_at': article.updated_at,
    }
    return Response(article_data)

 

/articles/index/

 


 

NEXT : Serializer

 

파이썬 장고 실무 심화 2주차 2_serializer, GET, POST

serializer를 사용하면 json 형태의 string으로 만들어 줌 GET articles > serializers.py: from rest_framework import serializers from articles.models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article

sw-ing.tistory.com