博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
REST_FRAMEWORK加深记忆-第二次练习官方文档2
阅读量:6848 次
发布时间: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://qbrul.baihongyu.com/

你可能感兴趣的文章
小白学爬虫-批量部署Splash负载集群
查看>>
你离BAT之间,只差这一套Java面试题
查看>>
laravel package 推荐,数据备份
查看>>
Synchronized锁在Spring事务管理下,为啥还线程不安全?
查看>>
环境变量PATH cp命令 mv命令 文档查看cat/more/less/head/tail
查看>>
阿里云亮相2019联通合作伙伴大会,边缘计算等3款云产品助力5G时代产业数字化转型...
查看>>
dubbo源码分析-服务端发布流程-笔记
查看>>
阿里云发布Apsara SA系列混合云存储阵列
查看>>
GoJS教程:链接模版
查看>>
QListWidget方式显示缩略图
查看>>
金三银四:蚂蚁金服JAVA后端面试题及答案之二面
查看>>
Ubuntu 外网不通解决方案
查看>>
OSChina 周六乱弹 —— 历史总是惊人的相似
查看>>
MySQL 大小写
查看>>
Lync 2013部署图片赏析-证书服务安装配置
查看>>
HTML5 本地缓存 (web存储)
查看>>
tomcat redis session共享(包含redis安全设置)
查看>>
iptables中DNAT、SNAT和MASQUERADE的作用
查看>>
kvm命令学习记录
查看>>
小菜鸡进阶之路-First week
查看>>