728x90
반응형
환경 설정
- pygments 설치
- snippets 앱 만들기
pip install pygments # We'll be using this for the code highlighting
cd tutorial
python manage.py startapp snippets
- settings.py의 INSTALLED_APPS에 snippets 추가
INSTALLED_APPS = [
...
'rest_framework',
'snippets',
]
Serializer 작성
모델 적용
모델 작성
- Snippet 모델 작성
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
class Meta:
ordering = ['created']
마이그레이션
python manage.py makemigrations snippets
python manage.py migrate snippets
Serializer 적용
Serializer class 작성
- 시리얼라이저는 crud를 담당함(orm이라 보면 됨)
- required, max_length 와 default 같은 validation flags를 사용할 수 있음
- 아래를 보면 {'base_template': 'textarea.html'} 이 있는데 이것은 장고 Form 클래스의 widget=widgets.Textarea 를 사용함
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
class SnippetSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=False, allow_blank=True, max_length=100)
code = serializers.CharField(style={'base_template': 'textarea.html'})
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
def create(self, validated_data):
"""
Create and return a new `Snippet` instance, given the validated data.
"""
return Snippet.objects.create(**validated_data)
def update(self, instance, validated_data):
"""
Update and return an existing `Snippet` instance, given the validated data.
"""
instance.title = validated_data.get('title', instance.title)
instance.code = validated_data.get('code', instance.code)
instance.linenos = validated_data.get('linenos', instance.linenos)
instance.language = validated_data.get('language', instance.language)
instance.style = validated_data.get('style', instance.style)
instance.save()
return instance
Serializer 실행
매니저로 쉘 실행
python manage.py shell
실행된 쉘에 아래 코드를 입력함
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
snippet = Snippet(code='foo = "bar"\n')
snippet.save()
snippet = Snippet(code='print("hello, world")\n')
snippet.save()
serializer = SnippetSerializer(snippet)
serializer.data
# 아래와 같은 결과를 볼 수 있음
# {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
Deserialization도 비슷하다. 아래와 같이 입력
import io
stream = io.BytesIO(content)
data = JSONParser().parse(stream)
serializer = SnippetSerializer(data=data)
serializer.is_valid()
# True
serializer.validated_data
# OrderedDict([('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
serializer.save()
# <Snippet: Snippet object>
Snippets.objects.all()과 many=True를 사용하면 여러 개를 한 번에 가져올 수 있음
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data
# [OrderedDict([('id', 1), ('title', ''), ('code', 'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', ''), ('code', 'print("hello, world")'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]
Model Serializer 적용
Model Serializer class 작성
- 아까보다 훨씬 간결해진 코드를 볼 수 있음
- 모델을 이용한 숏 컷 이기 때문에 코드에서 따로 validate를 하고 싶다면 Serializer를 사용 해야 함
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ['id', 'title', 'code', 'linenos', 'language', 'style']
Views 적용
Views 작성
- snippets/views.py에 작성
- @csrf_exempt 로 임시로 csrf 넘김
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
@csrf_exempt
def snippet_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = SnippetSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
@csrf_exempt
def snippet_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = SnippetSerializer(snippet)
return JsonResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = SnippetSerializer(snippet, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
snippet.delete()
return HttpResponse(status=204)
URLs 작성
snippets/urls.py에 작성
from django.urls import path
from snippets import views
urlpatterns = [
path('snippets/', views.snippet_list),
path('snippets/<int:pk>/', views.snippet_detail),
]
tutorial/urls.py에 작성
from django.urls import path, include
urlpatterns = [
path('', include('snippets.urls')),
]
테스트
서버 실행
python manage.py runserver
http://127.0.0.1:8000/snippets/ 로 입력하면 아래와 같이 json을 볼 수 있음
728x90
반응형
'Backend > Django' 카테고리의 다른 글
Django Tutorial 5: Relationships & Hyperlinked APIs (0) | 2024.03.12 |
---|---|
Django Tutorial 4: Authentication & Permissions (0) | 2024.03.10 |
Django Tutorial 3: Class-based Views (0) | 2024.03.10 |
Django Tutorial 2: Requests and Responses (0) | 2024.03.10 |
DjangoRestFramework 프로젝트 세팅 (0) | 2024.03.09 |