[Django REST API] Install
[Django REST API install]
settings.py 수정
'django_filters',
# Django Rest API Framework Settins
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser',
],
# 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'DEFAULT_PAGINATION_CLASS': 'api.pagination.aipassPagination',
'PAGE_SIZE': 20,
}
pip install drf-yasg
settings.py 수정
INSTALLED_APPS = [
...
'rest_framework',
'myapp',
# drf_yasg를 APPS에 추가
'drf_yasg'
]
app directory / yang.py
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,
)
app directory / urls.py
from . import yasg
urlpatterns = [
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'),
]
class Board(models.Model):
title = models.CharField(max_length=500)
description = models.TextField(blank=True, null=True)
content = RichTextUploadingField(blank=True, null=True)
view_count = models.IntegerField(default=0, blank=True)
display_order = models.IntegerField(default=0, blank=True, null=True)
open = models.IntegerField(choices=codes.YESNO, default=0)
popup = models.IntegerField(choices=codes.YESNO, default=0)
status = models.IntegerField(choices=codes.STATUS, default=1)
creator = models.ForeignKey(User, on_delete=models.PROTECT, related_name='board_creator', null=True, blank=True)
modifier = models.ForeignKey(User, on_delete=models.PROTECT, related_name='board_modifier', null=True, blank=True)
created = models.DateTimeField(default=timezone.now)
modified = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
''' On save, update timestamps '''
user = get_current_user()
if not self.id:
self.created = timezone.now()
try:
self.creator = user
except:
self.creator = self.creator
self.modified = timezone.now()
try:
self.modifier = user
except:
self.modifier = self.modifier
return super(Board, self).save(*args, **kwargs)
class BoardAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'display_order', 'open', 'popup', 'status')
readonly_fields = ('creator', 'modifier', 'created', 'modified')
list_filter = ['status', 'open', 'popup']
list_display_links = ['title']
list_per_page = 10
admin.site.register(models.Board, BoardAdmin)
class BoardSerializer(serializers.ModelSerializer):
class Meta:
model = models.Board
fields = '__all__'
views.py
class BoardViewSet(viewsets.ModelViewSet):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
renderer_classes = [JSONRenderer]
queryset = models.Board.objects.all()
serializer_class = serializers.BoardSerializer
filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
filterset_fields = '__all__'
search_fields = ['title']
ordering_fields = '__all__'
ordering = ['created']
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'boards', views.BoardViewSet, basename='board')
urlpatterns = [
path('', include(router.urls)),
]
댓글
댓글 쓰기