rest frame work纪念版代码

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

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

Objective--C的Foundation frame之NSMutableArray代码

1 #import <Foundation/Foundation.h> 2 3 @interface Person : NSObject 4 5 @property (nonatomic, strong)NSString *personName; 6 - (id)initWithName:(NSString *)name; 7 8 @end 9 10 #import "Person.h" 11 12 @implementation Person 13 14 - (id)in

ios中创建可以拖动的view原理和实现详解(含代码)

有时候我们会需要在界面上拖动view;uiview是继承于uiresponder的,所以可以响应触摸相关的事件. 重点是以下一组方法: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event - (void)touchesEnded:(NSSet *)touches withEvent:(UIE

IOS Ui控件 修改位置和尺寸,代码添加控件

所有的UI控件最终都继承自UIView,UI控件的公共属性都定义在UIView中, UIView的常见属性 UIView *superview; 获得自己的父控件对象 NSArray *subviews; 获得自己的所有子控件对象 NSInteger tag; 控件的ID(标识),父控件可以通过tag来找到对应的子控件 CGAffineTransform transform; 控件的形变属性(可以设置旋转角度.比例缩放.平移等属性) CGRect frame; 控件所在矩形框在父控件中的位置和尺

Delphi中Frame的使用方法(2)

Frame在写代码时和一般组件有什么不同呢?比如(1)中的客户信息的frame,如果想重写客户编辑按钮的click事件,会发生什么呢: procedure TBusOnSiteManager.FrameCustomerButtonEditCustomerClick(Sender: TObject);begin  inherited;  FrameCustomer.ButtonEditCustomerClick(Sender); end; 可见,IDE会自动加上调用Frame中按钮click的方法

iOS代码添加视图约束

项目要做这样一个效果的启动页. 考虑到版本号是会不断变更的,因此采用动画效果启动页,让版本号动态加载iOS启动页动画效果 - 简书 考虑到屏幕适配问题,因此采用代码对视图添加约束.在添加约束的过程中遇到了一些问题,在此做一下记录和总结. 代码实现autolayout的注意点: 1.要先禁止autoresizing功能,设置view 的translatesAutoresizingMaskIntoConstraints 属性为 NO; 2.添加约束之前,一定要保证相关控件都已经在各自的父控件上.(就

(转)基于FFPMEG2.0版本的ffplay代码分析

ref:http://zzhhui.blog.sohu.com/304810230.html 背景说明 FFmpeg是一个开源,免费,跨平台的视频和音频流方案,它提供了一套完整的录制.转换以及流化音视频的解决方案.而ffplay是有ffmpeg官方提供的一个基于ffmpeg的简单播放器.学习ffplay对于播放器流程.ffmpeg的调用等等是一个非常好的例子.本文就是对ffplay的一个基本的流程剖析,很多细节内容还需要继续钻研. 注:本文师基于ffmpeg-2.0版本进行分析,具体代码行还请对

ROS turtlebot_follower :让机器人跟随我们移动

ROS turtlebot_follower 学习 首先在catkin_ws/src目录下载源码,地址:https://github.com/turtlebot/turtlebot_apps.git 了解代码见注释(其中有些地方我也不是很明白) follower.cpp #include <ros/ros.h> #include <pluginlib/class_list_macros.h> #include <nodelet/nodelet.h> #include &

sizeToFit的学习与认知

今天一扫前两日的坏心情,终于有心情平静下来,今天我是根据网络上的一些资料进行学习,今天学习的内容是 sizeToFit() 方法在不方便手动布局的场景中的使用. 首先感谢资料的提供者:参考1 参考2 参考3 今天的主要是看到了一个方法,sizeToFit 方法,就上网搜了一下,重点是了解了一下该方法如何应用 首先: 在调用sizeToFit的时候,系统会根据内容帮我布局一个它认为合适的大小.sizeToFit()方法声明再UIView中,所以所有继承于UIView的控件都可以调用该方法. siz

转 iphone分辨率

iPhone6分辨率与适配 分辨率和像素 经新xcode6模拟器验证(分辨率为pt,像素为真实pixel): iPhone5分辨率320x568,像素640x1136,@2x iPhone6分辨率375x667,像素750x1334,@2x iPhone6 Plus分辨率414x736,像素1242x2208,@3x,(注意,在这个分辨率下渲染后,图像等比降低pixel分辨率至1080p(1080x1920)) PaintCode做了几个图讲解的非常明了 自动适配 不处理时自动等比拉伸,如果在老