REST_FRAMEWORK加深记忆-第二次练习官方文档2

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了REST_FRAMEWORK加深记忆-第二次练习官方文档2相关的知识,希望对你有一定的参考价值。

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

 

MODELS.PY

from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles

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)

    class Meta:
        ordering = (created,)

 

URLS.PY

from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views

urlpatterns = [
    url(r^snippets/$, views.snippet_list),
    url(rsnippets/(?P<pk>[0-9]+)/$, views.snippet_detail),
]

urlpatterns = format_suffix_patterns(urlpatterns)

 

VIEWS.PY

from django.http import HttpResponse
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer


class JSONResponse(HttpResponse):

    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs[content_type] = application/json
        super(JSONResponse, self).__init__(content, **kwargs)

@csrf_exempt
def 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_exempt
def 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 serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES


class 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

技术分享

 

以上是关于REST_FRAMEWORK加深记忆-第二次练习官方文档2的主要内容,如果未能解决你的问题,请参考以下文章

REST_FRAMEWORK加深记忆-加了用户登陆认证,自定义权限的API接口

forward和redirect请求方式

重新温习,不但可以让自己对js更加的深刻认识,又能加深记忆,至此每天一次复习记录在此。

python第二次练习

Python练习_考试第二次

PAT甲级第二次真题练习