models.py
from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles from pygments.lexers import get_lexer_by_name from pygments.formatters.html import HtmlFormatter from pygments import highlight 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) owner = models.ForeignKey(‘auth.User‘, related_name=‘snippets‘) highlighted = models.TextField() def save(self, *args, **kwargs): lexer = get_lexer_by_name(self.language) linenos = self.linenos and ‘table‘ or False options = self.title and {‘title‘: self.title} or {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter) super(Snippet, self).save(*args, **kwargs) class Meta: ordering = (‘created‘,)
urls.py
__author__ = ‘CHENGANG882‘ from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from snippets import views urlpatterns = [ url(r‘^$‘, views.api_root), url(r‘^snippets/$‘, views.SnippetList.as_view(), name=‘snippet-list‘), url(r‘^snippets/(?P<pk>[0-9]+)/$‘, views.SnippetDetail.as_view(), name=‘snippet-detail‘), url(r‘^users/$‘, views.UserList.as_view(),name=‘user-list‘), url(r‘^users/(?P<pk>[0-9]+)/$‘, views.UserDetail.as_view(), name=‘user-detail‘), url(r‘^snippets/(?P<pk>[0-9]+)/highlight/$‘, views.SnippetHighlight.as_view(), name=‘snippet-highlight‘), ] urlpatterns = format_suffix_patterns(urlpatterns)
serializers.py
__author__ = ‘CHENGANG882‘ from rest_framework import serializers from .models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES from django.contrib.auth.models import User class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source=‘owner.username‘) highlight = serializers.HyperlinkedIdentityField(view_name=‘snippet-highlight‘, format=‘html‘) class Meta: model = Snippet fields = (‘url‘, ‘pk‘, ‘highlight‘, ‘owner‘, ‘title‘, ‘code‘, ‘linenos‘, ‘language‘, ‘style‘) class UserSerializer(serializers.HyperlinkedModelSerializer): snippets = serializers.HyperlinkedRelatedField(many=True, view_name=‘snippet-detail‘, read_only=True) class Meta: model = User fields = (‘url‘, ‘pk‘, ‘username‘, ‘snippets‘)
views.py
from rest_framework import generics from .models import Snippet from .serializers import SnippetSerializer, UserSerializer from django.contrib.auth.models import User from rest_framework import permissions from .permissons import IsOwnerOrReadOnly from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework import renderers # Create your views here. class SnippetList(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly) def perform_create(self, serializer): serializer.save(owner=self.request.user) class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly) class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer 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) @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) })
permissions.py
__author__ = ‘CHENGANG882‘ from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user
时间: 2024-11-02 10:20:37