博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
REST_FRAMEWORK加深记忆-第二次练习官方文档2
阅读量:6825 次
发布时间:2019-06-26

本文共 5517 字,大约阅读时间需要 18 分钟。

优化前和优化后的代码,融在一起,能看看进化的过程。

 

MODELS.PY

from django.db import modelsfrom pygments.lexers import get_all_lexersfrom pygments.styles import get_all_stylesLEXERS = [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)    class Meta:        ordering = ('created',)

 

URLS.PY

from django.conf.urls import urlfrom rest_framework.urlpatterns import format_suffix_patternsfrom snippets import viewsurlpatterns = [    url(r'^snippets/$', views.snippet_list),    url(r'snippets/(?P
[0-9]+)/$', views.snippet_detail),]urlpatterns = format_suffix_patterns(urlpatterns)

 

VIEWS.PY

from django.http import HttpResponsefrom rest_framework import statusfrom rest_framework.decorators import api_viewfrom rest_framework.response import Responsefrom django.views.decorators.csrf import csrf_exemptfrom rest_framework.renderers import JSONRendererfrom rest_framework.parsers import JSONParserfrom snippets.models import Snippetfrom snippets.serializers import SnippetSerializerclass JSONResponse(HttpResponse):    def __init__(self, data, **kwargs):        content = JSONRenderer().render(data)        kwargs['content_type'] = 'application/json'        super(JSONResponse, self).__init__(content, **kwargs)@csrf_exemptdef snippet_list_old(request):    if request.method == 'GET':        snippets = Snippet.objects.all()        serializer = SnippetSerializer(snippets, many=True)        return JSONResponse(serializer.data)    elif request.method == 'POST':        data = JSONParser().parse(request)        serializer = SnippetSerializer(data=data)        if serializer.is_valid():            serializer.save()            return JSONResponse(serializer.data, status=201)        return JSONResponse(serializer.errors, status=400)@csrf_exemptdef snippet_detail_old(request, pk):    try:        snippet = Snippet.objects.get(pk=pk)    except Snippet.DoesNotExist:        return HttpResponse(status=404)    if request.method == 'GET':        serializer = SnippetSerializer(snippet)        return JSONResponse(serializer.data)    elif request.method == 'PUT':        data = JSONParser().parse(request)        serializer = SnippetSerializer(snippet, data=data)        if serializer.is_valid():            serializer.save()            return JSONResponse(serializer.data)        return JSONResponse(serializer.errors, status=400)    elif request.method == 'DELETE':        snippet.delete()        return HttpResponse(status=204)@api_view(['GET', 'POST'])def snippet_list(request, format=None):    if request.method == 'GET':        snippets = Snippet.objects.all()        serializer = SnippetSerializer(snippets, many=True)        return Response(serializer.data)    elif request.method == 'POST':        serializer = SnippetSerializer(data=request.data)        if serializer.is_valid():            serializer.save()            return Response(serializer.data, status=status.HTTP_201_CREATED)        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)@api_view(['GET', 'PUT', 'DELETE'])def snippet_detail(request, pk, format=None):    try:        snippet = Snippet.objects.get(pk=pk)    except Snippet.DoesNotExist:        return Response(status=status.HTTP_404_NOT_FOUND)    if request.method == 'GET':        serializer = SnippetSerializer(snippet)        return Response(serializer.data)    elif request.method == 'PUT':        serializer = SnippetSerializer(snippet, data=request.data)        if serializer.is_valid():            serializer.save()            return Response(serializer.data)        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)    elif request.method == 'DELETE':        snippet.delete()        return Response(status=status.HTTP_204_NO_CONTENT)

 

SERIALIZER.PY

from rest_framework import serializersfrom snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICESclass SnippetSerializer(serializers.ModelSerializer):    class Meta:        model = Snippet        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')class SnippetSerializerOld(serializers.Serializer):    pk = serializers.IntegerField(read_only=True)    title = serializers.CharField(required=False, allow_blank=True, max_length=100)    code = serializers.CharField(style={
'base_template': 'textarea.html'}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES,default='friendly') def create(self, validated_data): return Snippet.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = validated_data.get('linenos', instance.linenos) instance.language = validated_data.get('language', instance.language) instance.style = validated_data.get('style', instance.style) instance.save() return instance

 

转载地址:http://illzl.baihongyu.com/

你可能感兴趣的文章
黑马程序员-Foundation-NSArry的遍历
查看>>
Nodejs 文件上传
查看>>
数据挖掘之权重计算(PageRank)
查看>>
.net mvc + layui做图片上传(一)
查看>>
Shell命令_文件系统常用命令df、du
查看>>
6:7 题一起MySQL数据库分库备份
查看>>
mysql 授权的时候库名不能添加单引号homestead.* 写成 '库名'.* 错的语法
查看>>
编程有感:所欠的都会还的
查看>>
进制与认识vs2012
查看>>
代理模式实现方式及优缺点对比
查看>>
SVN无法检出项目
查看>>
sql去除重复数据 保留一条
查看>>
语言和文法的基本概念
查看>>
Skiing(最短路)
查看>>
洛谷——P3152 正整数序列
查看>>
查找大目录
查看>>
新手小白 python之路 Day6 (装饰器、生成器、迭代器)
查看>>
iptables详解
查看>>
数据结构之败者树
查看>>
Python列表中查找某个元素的索引(多个)
查看>>