[Django Install] 5. Django REST API Framework
settings.py 수정
'django_filters',
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware', # corsheaders 추가
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
'http://192.168.56.1:3000',
]
CORS_ORIGIN_REGEX_WHITELIST = [
'http://192.168.56.1:3000',
]
cd
cd [project]
python manage.py startapp api
api
__init__.py
migrations
templates (신규생성 필요)
api (신규생성 필요)
*.html (신규생성 필요)
static (신규생성 필요)
api (신규생성 필요)
css (신규생성 필요)
images (신규생성 필요)
js (신규생성 필요)
sass (신규생성 필요)
admin.py
apps.py
models.py
tests.py
views.py
project/project/settings.py에 아래 내용 추가
INSTALLED_APPS = [
...
'drf_yasg',
...
]
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
]
if settings.DEBUG is True:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# from django.conf.urls import url
from django.urls import path, include
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="aiPass API",
default_version='v1',
description="aiPass API description",
terms_of_service="https://www.google.com/policies/terms/",
contact=openapi.Contact(email="prefity@gmail.com"),
license=openapi.License(name="BSD License"),
),
validators=['flex'],
public=True,
permission_classes=(permissions.AllowAny,),
# patterns=schema_url_patterns,
)
from django.urls import include, path
from rest_framework import routers
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
from . import views, yasg
router = routers.DefaultRouter()
# router.register(r'users', views.UserViewSet, basename='user')
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('swagger<str:format>', yasg.schema_view.without_ui(cache_timeout=0), name='schema-json'),
path('swagger/', yasg.schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
path('docs/', yasg.schema_view.with_ui('redoc', cache_timeout=0), name='schema-redic'),
]
INSTALLED_APPS = [
...
'rest_framework.authtoken',
...
]
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from rest_framework.authtoken.models import Token
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
class ApiAuthToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({
'token': token.key,
'username': user.username,
'email': user.email
})
from django.urls import include, path
from rest_framework import routers
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
from . import views, yasg
router = routers.DefaultRouter()
router.register(r'lottos', views.LottoViewSet, basename='lotto')
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('api_token_auth/', views.ApiAuthToken.as_view()),
path('swagger<str:format>', yasg.schema_view.without_ui(cache_timeout=0), name='schema-json'),
path('swagger/', yasg.schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
path('docs/', yasg.schema_view.with_ui('redoc', cache_timeout=0), name='schema-redic'),
]
admin 화면에서 사용자 생성 시 token이 잘 생성되는지 확인.
from django.db import models
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.contrib.auth.models import User
from django.utils.html import strip_tags
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from datetime import date
import logging
logger = logging.getLogger('api')
# Schema
class Lotto(models.Model):
round = models.IntegerField(default=0)
date = models.DateField()
lotto1 = models.IntegerField(default=0)
lotto2 = models.IntegerField(default=0)
lotto3 = models.IntegerField(default=0)
lotto4 = models.IntegerField(default=0)
lotto5 = models.IntegerField(default=0)
lotto6 = models.IntegerField(default=0)
lotto7 = models.IntegerField(default=0)
lotto1_winner = models.IntegerField(default=0)
lotto2_winner = models.IntegerField(default=0)
lotto3_winner = models.IntegerField(default=0)
lotto4_winner = models.IntegerField(default=0)
lotto5_winner = models.IntegerField(default=0)
lotto1_winning = models.IntegerField(default=0)
lotto2_winning = models.IntegerField(default=0)
lotto3_winning = models.IntegerField(default=0)
lotto4_winning = models.IntegerField(default=0)
lotto5_winning = models.IntegerField(default=0)
python manage.py migrate
[api admin 적용]
project/app/admin.py 에서 모델을 어드민에 등록
from django.contrib import admin
from django.utils.safestring import mark_safe
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from . import models
class LottoAdmin(admin.ModelAdmin):
list_display = ('id', 'round', 'date', 'lotto1', 'lotto2', 'lotto3', 'lotto4', 'lotto5', 'lotto6', 'lotto7')
list_display_links = ['round']
list_per_page = 10
# unregister old user admin
admin.site.unregister(User)
# register new user admin
admin.site.register(User, UserAdmin)
admin.site.register(models.Lotto, LottoAdmin)
project/app/serializers.py
from django.contrib.auth.models import User, Group
from django.contrib.auth import authenticate
from django.conf import settings
from rest_framework import pagination
from rest_framework.response import Response
from rest_framework import serializers
from . import models
import logging
logger = logging.getLogger('api')
# Serializer
class LottoSerializer(serializers.ModelSerializer):
class Meta:
model = models.Lotto
fields = '__all__'
[api views 작성]
project/app/views.py
class LottoViewSet(viewsets.ModelViewSet):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
renderer_classes = [JSONRenderer]
queryset = models.Lotto.objects.all()
serializer_class = serializers.LottoSerializer
filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
filterset_fields = '__all__'
search_fields = ['round']
ordering_fields = '__all__'
ordering = ['date']
------------------
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.decorators import action, api_view, permission_classes
class RaViewSet(viewsets.ViewSet):
def list(self, request):
pid = request.query_params.get('pid', None)
return Response("list" + pid)
@action(detail=True, methods=['get'])
def ratest(self, request, pk=None):
pid = request.query_params.get('pid', None)
return Response("list" + pid)
project/app/urls.py
from django.urls import include, path
from rest_framework import routers
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
from . import views, yasg
router = routers.DefaultRouter()
router.register(r'lottos', views.LottoViewSet, basename='lotto')
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('swagger<str:format>', yasg.schema_view.without_ui(cache_timeout=0), name='schema-json'),
path('swagger/', yasg.schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
path('docs/', yasg.schema_view.with_ui('redoc', cache_timeout=0), name='schema-redic'),
]
댓글
댓글 쓰기