toolbar的配置和Django,python中序列化

一、django框架的体系化

一向上代码

1、这是app下的models.py

from django.db import models

# Create your models here.



class Course(models.Model):
    title=models.CharField(max_length=32)

二、那是app下的view.py,三种系列化方法

from django.views import View
from app01.models import Course


class CourseView(View):

    def get(self,request):

        ret=Course.objects.all()
        #这是我们自己用json模块去序列化数据
        #import json
        #temp=[] 
        # for i in ret:
        #     temp.append({
        #         "title":i.title
        #    })

        #这是django自带的
         from django.core.serializers import serialize
         ret=serialize("json",ret)

         # return HttpResponse(temp)     
         return HttpResponse(ret)

总结:

  大家会开采系列化出来的多寡比较单纯,重回来的体制太难为,而django自带的法门,而且没办法反种类化!

翻阅目录

#coding: utf-8
import sys, cPickle, json
import msgpack

obj = [[1, 2, 3], 123, 123.123, 'abc', {'键1': (1, 2, 3), '键2': (4, 5, 6)}]
print obj

#使用cPickle序列化
ser = cPickle.dumps(obj,True)
print ser
print cPickle.loads(ser)
#获取此对象在内存中所占的字节数
print sys.getsizeof(ser)

#转为json
ser = json.dumps(obj)
print ser
print sys.getsizeof(ser)

#转为MessagePack
ser = msgpack.packb(obj, use_bin_type=True)
print ser
print msgpack.unpackb(ser, encoding='utf-8')
print sys.getsizeof(ser)

Django Rest Framework 连串化关系模型

二、rest_framework中的系列化组件

toolbar的配置和Django,python中序列化。 首先大家要先下载那些模块

pip3 install djangorestframework

装好之后,不要忘了在app中注册rest_framework,

from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from django.shortcuts import HttpResponsefrom rest_framework import serializers

class BookSerializers(serializers.Serializer):  
    title=serializers.CharField(max_length=32)
    price=serializers.IntegerField()
    pub_date=serializers.DateField()
    publish=serializers.CharField(source="publish.name")
    #authors=serializers.CharField(source="authors.all")
    authors=serializers.SerializerMethodField()
    def get_authors(self,obj):
        temp=[]
        for author in obj.authors.all():
            data=[]
       data.append(author.pk) 
       data.append(author.name)
       temp.append(data)
        return temp

class BookViewSet(APIView):
    def get(self,request,*args,**kwargs):
        book_list=Book.objects.all()  
        bs=BookSerializers(book_list,many=True)
        return Response(bs.data)

大家这边有更简便的措施:

from rest_framework import serializers
from app01.models import Book
class BookSerializers(serializers.ModelSerializer):
    class Meta:
        model=Book
        fields="__all__"

 八种景况的正规化情势

class BookView(APIView):

    def get(self, request):
        book_list = Book.objects.all()
        bs = BookSerializers(book_list, many=True)
        # 序列化数据
        return Response(bs.data)

    def post(self, request):
        # 添加一条数据
        print(request.data)
        bs=BookSerializers(data=request.data)
        if bs.is_valid():
            bs.save()  # 生成记录
            return Response(bs.data)
        else:
            return Response(bs.errors)

class BookDetailView(APIView):
    def get(self,request,pk):
        book_obj=Book.objects.filter(pk=pk).first()
        bs=BookSerializers(book_obj,many=False)
        return Response(bs.data)

    def put(self,request,pk):
        book_obj = Book.objects.filter(pk=pk).first()
        bs=BookSerializers(data=request.data,instance=book_obj)#instance
        if bs.is_valid():
            bs.save() # update
            return Response(bs.data)
        else:
            return Response(bs.errors)

    def delete(self,request,pk):
        Book.objects.filter(pk=pk).delete()
        return Response("")

大家再次创下造一张表,大家会发觉代码有点冗余了,除了变量名的变化,这里也有封好的章程mixin类

from rest_framework import mixins
from rest_framework import generics

class BookViewSet(mixins.ListModelMixin,
                  mixins.CreateModelMixin,
                  generics.GenericAPIView):

    queryset = Book.objects.all()
    serializer_class = BookSerializers

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)



class BookDetailViewSet(mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    generics.GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializers

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

咱俩在上面包车型客车多少个类中,大家下去翻看源码:

from rest_framework.mixins import CreateModelMixin
from rest_framework.mixins import ListModelMixin
from rest_framework.mixins import DestroyModelMixin
from rest_framework.mixins import RetrieveModelMixin
from rest_framework.mixins import UpdateModelMixin

咱俩先来看CreateModeMixin类的源码,大家开采 create 

图片 1

ListModeMixin类的源码,大家开掘list

 图片 2

RetrieveModelMixin类的源码,大家开掘retrieve

图片 3

UpdateModelMixin类的源码,我们开采update

 图片 4

DestroyModelMixin类的源码,我们挖掘destroy

图片 5

然后大家可以这样封装:

from rest_framework.mixins import CreateModelMixin,ListModelMixin,DestroyModelMixin,RetrieveModelMixin,UpdateModelMixin
from rest_framework import generics

class BookView(CreateModelMixin,ListModelMixin,generics.GenericAPIView,):

    queryset=Book.objects.all()
    serializer_class=BookSerializers

    def get(self,request):
        return self.list(request)

    def post(self,request):

        return self.create(request)

class BookDetailView(DestroyModelMixin,UpdateModelMixin,RetrieveModelMixin,generics.GenericAPIView,):
    queryset = Book.objects.all()
    serializer_class = BookSerializers

    def get(self,request, *args, **kwargs):

       return self.retrieve(request, *args, **kwargs)

    def put(self,request, *args, **kwargs):

       return self.update(request, *args, **kwargs)

    def delete(self,request, *args, **kwargs):

        return self.destroy(request, *args, **kwargs)

发觉代码仍旧冗余的,我们还有更方便的措施,REST框架提供了简化的view.py模块

from rest_framework import mixins
from rest_framework import generics

class BookViewSet(generics.ListCreateAPIView):

    queryset = Book.objects.all()
    serializer_class = BookSerializers

class BookDetailViewSet(generics.RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializers

class PublishViewSet(generics.ListCreateAPIView):

    queryset = Publish.objects.all()
    serializer_class = PublshSerializers

class PublishDetailViewSet(generics.RetrieveUpdateDestroyAPIView):
    queryset = Publish.objects.all()
    serializer_class = PublshSerializers

急需怎么着的法子,就三番五次什么方法类,但里面包车型客车办法要求在url传入需求的参数

#views中代码非常简介,最重要的还是urls
from rest_framework.viewsets import ModelViewSet

class AuthorModelView(ModelViewSet):

    queryset=Author.objects.all()
    serializer_class=AuthorSerializers

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    #在as_view中加入参数
    url(r'^authors/$', views.AuthorModelView.as_view({"get":"list","post":"create"})),
    url(r'^authors/(?P<pk>\d+)/$', views.AuthorModelView.as_view({"get":"retrieve","put":"update","delete":"destroy"})),
]

 

  1. django-debug-toolbar的配置
  2. Django
    logging的配置

segmentfault.com/a/1190000010024982

一、django-debug-toolbar的配置

变化嵌套的json数据格式:

1、介绍

django-debug-toolbar
是一组可布署的面板,可兆示有关当前呼吁/响应的各个调试消息,并在单击时显示有关面板内容的越来越多详细音信。

github地址

文书档案地址

参考作品 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图