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

rest frame work纪念版代码的更多相关文章

  1. 【路径规划】 Optimal Trajectory Generation for Dynamic Street Scenarios in a Frenet Frame (附python代码实例)

    参考与前言 2010年,论文 Optimal Trajectory Generation for Dynamic Street Scenarios in a Frenet Frame 地址:https ...

  2. Busting Frame Busting: a Study of Clickjacking Vulnerabilities on Popular Sites

    Busting Frame Busting Reference From: http://seclab.stanford.edu/websec/framebusting/framebust.pdf T ...

  3. 定位frame 中的对象

    在web 应用中经常会出现frame 嵌套的应用,假设页面上有A.B 两个frame,其中B 在A 内,那么定位B 中的内容则需要先到A,然后再到B.switch_to_frame 方法可以把当前定位 ...

  4. webkit内核分析之 Frame

    参考地址:http://blog.csdn.net/dlmu2001/article/details/6164873 1.    描述 Frame类是WebCore内核同应用之间联系的一个重要的类.它 ...

  5. UIView.frame的骗局

    如果你刚刚开始接触IOS编程, 刚刚接触UIKit, 肯定会被 frame, bounds, center, layer.anchorPoint, layer.position 这些乱七八糟得属性折腾 ...

  6. Android动画主要包含补间动画(Tween)View Animation、帧动画(Frame)Drawable Animation、以及属性动画Property Animation

    程序运行效果图: Android动画主要包含补间动画(Tween)View Animation.帧动画(Frame)Drawable Animation.以及属性动画Property Animatio ...

  7. bounds 和 frame

    使用环境: 一个UIView 添加xib View 时需要注意使用 frame and bounds 代码: frame 和 bounds 对比 样式对比 其实说白了就是 frame: 该view在父 ...

  8. <Android 基础(二十五)> Frame Animation

    简介 Frame Animation, 逐帧动画,通过定义一系列的Drawable对象来实现动画效果,可以用来作为视图的背景. Frame Animation在代码中体现为AnimationDrawa ...

  9. unity代码添加动画,并传参数

    测试界面 button一个 sprite一个 测试代码 public class BgObject : MonoBehaviour { void Start() { List<string> ...

随机推荐

  1. ASP.NET SQL 总结(2)

    Sql常见面试题(总结) 1.用一条SQL语句 查询出每门课都大于80分的学生姓名 name   kecheng   fenshu 张三     语文       81 张三     数学       ...

  2. 【知识总结】多项式全家桶(三)(任意模数NTT)

    经过两个月的咕咕,"多项式全家桶" 系列终于迎来了第三期--(雾) 上一篇:[知识总结]多项式全家桶(二)(ln和exp) 先膜拜(伏地膜)大恐龙的博客:任意模数 NTT (在页面 ...

  3. Linq 内连接和外连接(转载)

    一.内连接 Model1Container model = new Model1Container(); //内连接 var query = from s in model.Student join ...

  4. 【C++】Item34.区分接口继承和实现继承

    区分接口继承和实现继承 类包含的成员函数种类 1.静态函数 2.非静态函数 2.1 普通函数(非虚) non-virtual 2.2 虚函数 2.2.1 纯虚函数 pure-virtual 2.2.2 ...

  5. Spark学习之基础相关组件(1)

    Spark学习之基础相关组件(1) 1. Spark是一个用来实现快速而通用的集群计算的平台. 2. Spark的一个主要特点是能够在内存中进行计算,因而更快. 3. RDD(resilient di ...

  6. XAMPP--Apache服务无法启动问题定位及处理

    一.问题简述: XAMPP 在使用一段时间后,Apache服务无法启动. 二.详细描述: 安装Xampp服务器套件之后,部署使用正常.一段时间未使用,再次打开时,Apache服务无法启动.错误提示如下 ...

  7. Git——基本操作

    Shell 基本概念 shell俗称壳,为使用者提供使用界面,例如DOS下command以及后来的cmd.exe shell分类 图形界面shell,提供友好的可视化界面,例如windows操作界面, ...

  8. 【译】x86程序员手册28-7.7任务地址空间

    7.7 Task Address Space 任务地址空间 The LDT selector and PDBR fields of the TSS give software systems desi ...

  9. 判断excel是否包含隐藏sheet

    Workbook workbook =new XSSFWorkbook("D:\\文档1.xlsx"); System.out.println(workbook.isSheetHi ...

  10. python利用requests统计1个接口的响应时间

    参照 https://www.cnblogs.com/yoyoketang/p/8035428.html requests统计接口的响应时间有2种方式 r.elapsed.total_seconds( ...