728x90
반응형
설치 후 requirements 에 삽입
pip install djangorestframework
pip freeze | grep djangorestframework >> requirements.txt
# requirements.txt
Django==4.2.3
gunicorn==21.2.0
psycopg2-binary==2.9.7
pymongo==4.4.1
djangorestframework==3.14.0
## Third party Apps
INSTALLED_APPS += [
'rest_framework',
]
project - urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include(blog_urls)),
path('api-auth/', include('rest_framework.urls')),
]
변동사항 적용
docker-compose -f ../docker-compose.yml up --build -d
이제 모델을 통해 저장된 정보를 JSON 형태로 (씨리얼라이즈) 바꿔서 전달할 수 있게 해야한다.
blog app - serializers.py
from rest_framework import serializers
from pymongo import MongoClient
client = MongoClient(host="mongo")
db = client.likelion
class BlogSerializer(serializers.Serializer):
title = serializers.CharField(max_length=100)
content = serializers.CharField()
author = serializers.CharField(max_length=100)
def create(self, validated_data):
return db.blogs.insert_one(validated_data)
app - urls.py
from django.urls import path
from rest_framework.routers import DefaultRouter
from . import views
# urlpatterns= [
# path('', views.create_blog, name='blog-create'),
# ]
router = DefaultRouter()
router.register('', views.BlogViewSet, basename='blog')
app -views.py
# 내장 라이브러리
# Third party 라이브러리
from pymongo import MongoClient
from django.http import JsonResponse
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status
# my 라이브러리
from .serializers import BlogSerializer
client = MongoClient(host="mongo")
db = client.likelion
class BlogViewSet(ViewSet):
# Define serializer
serializer_class = BlogSerializer
def list(self, request):
return Response(status=status.HTTP_200_OK)
def create(self, request):
"""
request.data = {
"title" : "My first blog",
"content" : "This is my first blog",
"author" : "lion",
}
"""
serializer = BlogSerializer(data=request.data)
if serializer.is_valid():
serializer.create(serializer.validated_data)
# serializer.save()
return Response(status=status.HTTP_201_CREATED, data=serializer.data)
else:
return Response(status=status.HTTP_400_BAD_REQUEST, data=serializer.errors)
def update(self, request):
pass
def retrieve(self, request):
pass
def destroy(self, request):
pass
def create_blog(rquest) -> bool:
blog = {
"title" : "My first blog",
"content" : "This is my first blog",
"author" : "lion",
}
try:
db.blogs.insert_one(blog)
return True
except Exception as e:
print(e)
return False
def update_blog():
pass
def delete_blog():
pass
def read_blog():
pass
run it on container
docker-compose -f ../docker-compose.yml up --build -d
Get back the static files (CSS)
docker-compose exec lion-app python manage.py collectstatic
Run it agin
728x90
반응형
'Dev. > Django & DRF' 카테고리의 다른 글
Django : DRF 적용하기3 - Spectacular (0) | 2023.08.16 |
---|---|
Django : DRF 적용하기2 (0) | 2023.08.16 |
Django : DRF - quick start (0) | 2023.08.15 |
Django : 시작하기 (0) | 2023.08.09 |
Django : 프로그램 구조 이해하기 (0) | 2023.08.02 |
댓글