프로젝트 소개

RESTful API를 가지고 3개의 게시판을 만들어보자

  • 글을 쓸 수 있는 Essay
  • 이미지를 올릴 수 있는 Album
  • 파일을 올릴 수 있는 Files

코드

라이브러리

1
2
$ pip install djangorestframework #DRF 
$ pip install Pillow #이미지

settings.py

1
2
3
4
5
6
7
8
9
10
INSTALLED_APPS = [
#rest_framework 등록
'rest_framework',
# app 등록
'mystorage'
]

# 이미지를 등록하기위해 Media 경로지정
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

models.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from django.db import models
from django.conf import settings

class Essay(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, default =1, on_delete = models.CASCADE)
title = models.CharField(max_length=100)
body = models.TextField()

class Album(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, default =1, on_delete = models.CASCADE)
image = models.ImageField(upload_to="images")
desc = models.CharField(max_length=100)

class Files(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, default =1, on_delete = models.CASCADE)
myfile = models.FileField(upload_to="files", blank=False, null= False)
desc = models.CharField(max_length=100)

DB 적용

1
2
python manage.py makemigrations
python manage.py migrate

serializers.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from .models import Essay, Album, Files
from rest_framework import serializers

class EssaySerializer(serializers.ModelSerializer):

# 글쓴이를 자동적으로 등록함
author_name = serializers.ReadOnlyField(source='author.username')

class Meta:
model = Essay
# fields = '__all__'
fields = ('pk', 'title' , 'body', 'author_name')

# def perform_create(self, serializer):
# serializer.save(author = self.request.user)

class AlbumSerializer(serializers.ModelSerializer):

# 글쓴이를 자동적으로 등록함
author_name = serializers.ReadOnlyField(source='author.username')
# 이미지를 업로드하고 결과값을 url로 하겠다
image = serializers.ImageField(use_url=True)
class Meta:
model = Album
fields = ('pk', 'author_name' , 'image', 'desc')


class FilesSerializer(serializers.ModelSerializer):

# 글쓴이를 자동적으로 등록함
author_name = serializers.ReadOnlyField(source='author.username')
myfile = serializers.FileField(use_url= True)

class Meta:
model = Files
fields = ('pk', 'author_name' , 'myfile', 'desc')

urls.py (PROJECT)

1
2
3
4
5
6
7
8
9
10
11
12
from django.contrib import admin
from django.urls import path, include
from mystorage import urls
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
path('admin/', admin.site.urls),
# url 연결
path('', include('mystorage.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urls.py (APP)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from rest_framework.routers import DefaultRouter
from mystorage import views
from django.urls import path, include
from rest_framework import urls

# DefaultRouter기반의 라우터 등록
router = DefaultRouter()

router.register('essay', views.PostViewSet)
router.register('album', views.ImgViewSet)
router.register('files', views.FileViewSet)

urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls')),
]

views.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from rest_framework import viewsets
from .models import Essay , Album, Files
from .serializers import EssaySerializer, AlbumSerializer, FilesSerializer
from rest_framework.filters import SearchFilter
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
from rest_framework import status

# ModelViewSet 두가지 객체 - queryset / serializer_class
class PostViewSet(viewsets.ModelViewSet):
queryset = Essay.objects.all()
serializer_class = EssaySerializer

# 검색 기능
filter_backends = [SearchFilter]
search_fields = ('title', 'body')

# 현재 request를 보낸 유저
# == self.request.user
def get_queryset(self):
qs = super().get_queryset()
if self.request.user.is_authenticated:
qs = qs.filter(author= self.request.user)
else:
qs = qs.none()
return qs

class ImgViewSet(viewsets.ModelViewSet):

queryset = Album.objects.all()
serializer_class = AlbumSerializer

# 다양한 미디어 파일을 받아야하기 때문에 지정해줘야함

class FileViewSet(viewsets.ModelViewSet):
queryset = Files.objects.all()
serializer_class = FilesSerializer

# parser_class 지정
parser_classes = (MultiPartParser, FormParser)

# create() 오버라이딩 / API HTTP -> get() post() 오버라이딩
def post(self, request, *arg, **kwargs):
serializer = FilesSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status= HTTP_201_CREATED)

else:
return Response(serializer.error, status = HTTP_400_BAD_REQUEST)

실행화면

Main
Result

하루를 기록하다