This repository has been archived on 2022-09-23. You can view files and clone it, but cannot push or open issues or pull requests.
webdev/website/snippets/views.py

46 lines
1.6 KiB
Python
Raw Normal View History

2022-01-08 00:40:31 +01:00
from django.contrib.auth.models import User
2022-01-08 00:12:34 +01:00
from .models import Snippet
2022-01-08 00:40:31 +01:00
from .serializers import SnippetSerializer, UserSerializer
from .permissions import IsOwnerOrReadOnly
2022-01-08 02:19:47 +01:00
from rest_framework import generics, permissions, renderers
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
@api_view(['GET'])
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'snippets': reverse('snippet-list', request=request, format=format)
})
2022-01-08 00:29:57 +01:00
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
2022-01-08 00:48:12 +01:00
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
2022-01-08 00:12:34 +01:00
2022-01-08 00:43:06 +01:00
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
2022-01-08 00:12:34 +01:00
2022-01-08 00:29:57 +01:00
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all()
2022-01-08 00:40:31 +01:00
serializer_class = SnippetSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
2022-01-08 00:40:31 +01:00
2022-01-08 02:19:47 +01:00
class SnippetHighlight(generics.GenericAPIView):
queryset = Snippet.objects.all()
renderer_classes = [renderers.StaticHTMLRenderer]
def get(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)
2022-01-08 00:40:31 +01:00
class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer