프로젝트 소개 RESTful API를 가지고 3개의 게시판을 만들어보자
글을 쓸 수 있는 Essay
이미지를 올릴 수 있는 Album
파일을 올릴 수 있는 Files
코드 라이브러리 1 2 $ pip install djangorestframework $ pip install Pillow
settings.py 1 2 3 4 5 6 7 8 9 10 INSTALLED_APPS = [ 'rest_framework' , 'mystorage' ] 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 modelsfrom django.conf import settingsclass 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, Filesfrom rest_framework import serializersclass EssaySerializer (serializers.ModelSerializer ): author_name = serializers.ReadOnlyField(source='author.username' ) class Meta : model = Essay fields = ('pk' , 'title' , 'body' , 'author_name' ) class AlbumSerializer (serializers.ModelSerializer ): author_name = serializers.ReadOnlyField(source='author.username' ) 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 adminfrom django.urls import path, includefrom mystorage import urlsfrom django.conf import settingsfrom django.conf.urls.static import staticurlpatterns = [ path('admin/' , admin.site.urls), 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 DefaultRouterfrom mystorage import viewsfrom django.urls import path, includefrom rest_framework import urlsrouter = 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 viewsetsfrom .models import Essay , Album, Filesfrom .serializers import EssaySerializer, AlbumSerializer, FilesSerializerfrom rest_framework.filters import SearchFilterfrom rest_framework.parsers import MultiPartParser, FormParserfrom rest_framework.response import Responsefrom rest_framework import statusclass PostViewSet (viewsets.ModelViewSet ): queryset = Essay.objects.all () serializer_class = EssaySerializer filter_backends = [SearchFilter] search_fields = ('title' , 'body' ) 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_classes = (MultiPartParser, FormParser) 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)
실행화면
하루를 기록하다