• 运维开发笔记整理-序列化


                  运维开发笔记整理-序列化

                                   作者:尹正杰

    版权声明:原创作品,谢绝转载!否则将追究法律责任。

    一.准备环境

    1>.创建一个apps 

    python manage.py startapp idcs

    2>. 创建一个apps的包,以后将创建的项目都移动至改目录中并配置相应的环境目录。这样做的目录是便于管理,否则随着项目的增多,咱们的根目录的文件夹也越多

    import sys
    sys.path.insert(0,os.path.join(BASE_DIR,"apps"))      #我们需要使用sys模块将BASE_DIR下的“apps”加入环境变了的第一个位置!

     

    3>.检查idcs.apps.IdcsConfig中的name的值是否正确,如下图所示:

    4>.安装与配置Django rest framework框架

    bogon:~ yinzhengjie$ pip3.6 install djangorestframework
    Collecting djangorestframework
      Downloading https://files.pythonhosted.org/packages/ef/13/0f394111124e0242bf3052c5578974e88e62e3715f0daf76b7c987fc6705/djangorestframework-3.9.1-py2.py3-none-any.whl (950kB)
        100% |████████████████████████████████| 952kB 18kB/s 
    Installing collected packages: djangorestframework
    Successfully installed djangorestframework-3.9.1
    You are using pip version 19.0.2, however version 19.0.3 is available.
    You should consider upgrading via the 'pip install --upgrade pip' command.
    bogon:~ yinzhengjie$ 
    pip3.6 install djangorestframework
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'idcs.apps.IdcsConfig',
        #'rest_framework',            #我们配置上改模块即可!若没有饮用改模块的话,那就最好将其注视掉,如果要用,直接在代码李import即可!
    ]

    5>.修改idcs.models.py配置文件

    from django.db import models
    
    # Create your models here.
    class Idc(models.Model):
        name    = models.CharField("机房名称",max_length=32)
        address = models.CharField("机房地址",max_length=256)
        phone   = models.CharField("联系人",max_length=15)
        email   = models.EmailField("邮件地址",default="null")
        letter  = models.CharField("IDC简称",max_length=5)
    
        def __str__(self):
            return self.name
    
        class Meta:
            db_table = "resources_idc"

    6>.查看数据库的表结构

    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py showmigrations
    admin
     [ ] 0001_initial
     [ ] 0002_logentry_remove_auto_add
    auth
     [ ] 0001_initial
     [ ] 0002_alter_permission_name_max_length
     [ ] 0003_alter_user_email_max_length
     [ ] 0004_alter_user_username_opts
     [ ] 0005_alter_user_last_login_null
     [ ] 0006_require_contenttypes_0002
     [ ] 0007_alter_validators_add_error_messages
     [ ] 0008_alter_user_username_max_length
    contenttypes
     [ ] 0001_initial
     [ ] 0002_remove_content_type_name
    idcs
     (no migrations)
    sessions
     [ ] 0001_initial
    (venv) bogon:yinzhengjie_devops yinzhengjie$  
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py showmigrations                  #查看那些表没有同步!
    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py migrate
    Operations to perform:
      Apply all migrations: admin, auth, contenttypes, sessions
    Running migrations:
      Applying contenttypes.0001_initial... OK
      Applying auth.0001_initial... OK
      Applying admin.0001_initial... OK
      Applying admin.0002_logentry_remove_auto_add... OK
      Applying contenttypes.0002_remove_content_type_name... OK
      Applying auth.0002_alter_permission_name_max_length... OK
      Applying auth.0003_alter_user_email_max_length... OK
      Applying auth.0004_alter_user_username_opts... OK
      Applying auth.0005_alter_user_last_login_null... OK
      Applying auth.0006_require_contenttypes_0002... OK
      Applying auth.0007_alter_validators_add_error_messages... OK
      Applying auth.0008_alter_user_username_max_length... OK
      Applying sessions.0001_initial... OK
    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py showmigrations
    admin
     [X] 0001_initial
     [X] 0002_logentry_remove_auto_add
    auth
     [X] 0001_initial
     [X] 0002_alter_permission_name_max_length
     [X] 0003_alter_user_email_max_length
     [X] 0004_alter_user_username_opts
     [X] 0005_alter_user_last_login_null
     [X] 0006_require_contenttypes_0002
     [X] 0007_alter_validators_add_error_messages
     [X] 0008_alter_user_username_max_length
    contenttypes
     [X] 0001_initial
     [X] 0002_remove_content_type_name
    idcs
     (no migrations)                      #我们发现就apps还没有同步!其他的表已经同步到数据库啦!
    sessions
     [X] 0001_initial
    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py migrate                      #同步元数据信息
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py showmigrations
    admin
     [X] 0001_initial
     [X] 0002_logentry_remove_auto_add
    auth
     [X] 0001_initial
     [X] 0002_alter_permission_name_max_length
     [X] 0003_alter_user_email_max_length
     [X] 0004_alter_user_username_opts
     [X] 0005_alter_user_last_login_null
     [X] 0006_require_contenttypes_0002
     [X] 0007_alter_validators_add_error_messages
     [X] 0008_alter_user_username_max_length
    contenttypes
     [X] 0001_initial
     [X] 0002_remove_content_type_name
    idcs
     (no migrations)
    sessions
     [X] 0001_initial
    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py  makemigrations idcs              #为idcs生成新的签名
    Migrations for 'idcs':
      apps/idcs/migrations/0001_initial.py
        - Create model Idc
    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py showmigrations
    admin
     [X] 0001_initial
     [X] 0002_logentry_remove_auto_add
    auth
     [X] 0001_initial
     [X] 0002_alter_permission_name_max_length
     [X] 0003_alter_user_email_max_length
     [X] 0004_alter_user_username_opts
     [X] 0005_alter_user_last_login_null
     [X] 0006_require_contenttypes_0002
     [X] 0007_alter_validators_add_error_messages
     [X] 0008_alter_user_username_max_length
    contenttypes
     [X] 0001_initial
     [X] 0002_remove_content_type_name
    idcs
     [ ] 0001_initial                  #就这一个数据库还没有同步信息呢!其他的都已经同步啦~
    sessions
     [X] 0001_initial
    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py makemigrations idcs                #为idcs生成新的签名
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py showmigrations
    admin
     [X] 0001_initial
     [X] 0002_logentry_remove_auto_add
    auth
     [X] 0001_initial
     [X] 0002_alter_permission_name_max_length
     [X] 0003_alter_user_email_max_length
     [X] 0004_alter_user_username_opts
     [X] 0005_alter_user_last_login_null
     [X] 0006_require_contenttypes_0002
     [X] 0007_alter_validators_add_error_messages
     [X] 0008_alter_user_username_max_length
    contenttypes
     [X] 0001_initial
     [X] 0002_remove_content_type_name
    idcs
     [ ] 0001_initial
    sessions
     [X] 0001_initial
    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py migrate idcs            #同步idcs表!
    Operations to perform:
      Apply all migrations: idcs
    Running migrations:
      Applying idcs.0001_initial... OK
    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py showmigrations
    admin
     [X] 0001_initial
     [X] 0002_logentry_remove_auto_add
    auth
     [X] 0001_initial
     [X] 0002_alter_permission_name_max_length
     [X] 0003_alter_user_email_max_length
     [X] 0004_alter_user_username_opts
     [X] 0005_alter_user_last_login_null
     [X] 0006_require_contenttypes_0002
     [X] 0007_alter_validators_add_error_messages
     [X] 0008_alter_user_username_max_length
    contenttypes
     [X] 0001_initial
     [X] 0002_remove_content_type_name
    idcs
     [X] 0001_initial
    sessions
     [X] 0001_initial
    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py migrate idcs                    #同步idcs表!

    7>.往数据库插入测试数据

    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py shell
    Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 26 2018, 19:50:54) 
    [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> 
    >>> from idcs.models import Idc
    >>> 
    >>> idc = Idc()
    >>> 
    >>> idc.name = "中国检验检疫科学研究员亦庄机房"
    >>> 
    >>> idc.address = "北京亦庄经济开发区荣华南路11号"
    >>> 
    >>> idc.phone = "010-53897343"
    >>> 
    >>> idc.email = 'yinzhengjie@mail.caiq.org.cn'
    >>> 
    >>> idc.letter = 'yz'
    >>> 
    >>> idc.save()
    >>> 
    >>> 
    >>> idc.id = None
    >>> 
    >>> 
    >>> idc.name = "中国检验检疫科学研究院高碑店机房"
    >>> 
    >>> idc.address = "高碑店"
    >>> 
    >>> idc.letter = "gbd"
    >>> 
    >>> idc.email = 'jky@mail.caiq.org.cn'
    >>> 
    >>> idc.save()
    >>> 
    >>> 
    添加2条测试数据详细信息步骤

      

    二.序列化模型

    1>.在idcs的apps中创建序列化文件,并编写序列化代码,如下图所示

    # !/usr/bin/env python
    # _*_conding:utf-8_*_
    # @author :yinzhengjie
    # blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    
    
    
    from rest_framework import serializers
    
    
    class IdcSerializer(serializers.Serializer):
        """
            IDC序列化类
        """
        id          = serializers.IntegerField()          #注意,我们这里定义变量的类型,这个类型是定义返回给前端的数据类型
        name        = serializers.CharField()
        address     = serializers.CharField()
        phone       = serializers.CharField()
        email       = serializers.EmailField()
        letter      = serializers.CharField()
    具体代码戳这里!

    2>.使用自定义的序列化类

    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py  shell
    Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 26 2018, 19:50:54) 
    [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> 
    >>> 
    >>> from idcs.serializers import IdcSerializer
    >>> 
    >>> from idcs.models import Idc
    >>> 
    >>> idc = Idc.objects.get(pk=1)
    >>> 
    >>> idc
    <Idc: 中国检验检疫科学研究员亦庄机房>
    >>> 
    >>> serializer = IdcSerializer(idc)
    >>> 
    >>> serializer
    IdcSerializer(<Idc: 中国检验检疫科学研究员亦庄机房>):
        id = IntegerField()
        name = CharField()
        address = CharField()
        phone = CharField()
        email = EmailField()
        letter = CharField()
    >>> 
    >>> 
    >>> serializer.data            #我们可以获取到数据!
    {'id': 1, 'name': '中国检验检疫科学研究员亦庄机房', 'address': '北京亦庄经济开发区荣华南路11号', 'phone': '010-53897343', 'email': 'yinzhengjie@mail.caiq.org.cn', 'letter': 'yz'}
    >>> 
    >>> 
    >> 
    >>> res = serializer.data
    >>> 
    >>> type(res)
    <class 'rest_framework.utils.serializer_helpers.ReturnDict'>
    >>> 
    >>> import json
    >>> 
    >>> json.dumps(res)              #不推荐使用这种方法直接转换成json格式,而是使用
    '{"id": 1, "name": "\u4e2d\u56fd\u68c0\u9a8c\u68c0\u75ab\u79d1\u5b66\u7814\u7a76\u5458\u4ea6\u5e84\u673a\u623f", "address": "\u5317\u4eac\u4ea6\u5e84\u7ecf\u6d4e\u5f00\u53d1\u533a\u8363\u534e\u5357\u8def11\u53f7", "phone": "010-53897343", "email": "yinzhengjie@mail.caiq.org.cn", "letter": "yz"}'
    >>> 
    >>>
    使用python 自带的模块进行序列化操作(不推荐使用,因为它没有做异常处理操作!)
    (venv) bogon:yinzhengjie_devops yinzhengjie$ 
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py  shell
    Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 26 2018, 19:50:54) 
    [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> 
    >>> 
    >>> from idcs.serializers import IdcSerializer
    >>> 
    >>> from idcs.models import Idc
    >>> 
    >>> idc = Idc.objects.get(pk=1)
    >>> 
    >>> idc
    <Idc: 中国检验检疫科学研究员亦庄机房>
    >>> 
    >>> serializer = IdcSerializer(idc)
    >>> 
    >>> serializer
    IdcSerializer(<Idc: 中国检验检疫科学研究员亦庄机房>):
        id = IntegerField()
        name = CharField()
        address = CharField()
        phone = CharField()
        email = EmailField()
        letter = CharField()
    >>> 
    >>> 
    >>> serializer.data            #我们可以获取到数据!
    {'id': 1, 'name': '中国检验检疫科学研究员亦庄机房', 'address': '北京亦庄经济开发区荣华南路11号', 'phone': '010-53897343', 'email': 'yinzhengjie@mail.caiq.org.cn', 'letter': 'yz'}
    >>> 
    >>> 
    >> 
    >>> res = serializer.data
    >>> 
    >>> 
    >>> from rest_framework.renderers import JSONRenderer
    >>> 
    >>> jr = JSONRenderer()
    >>> 
    >>> jr.render(serializer.data)
    b'{"id":1,"name":"xe4xb8xadxe5x9bxbdxe6xa3x80xe9xaax8cxe6xa3x80xe7x96xabxe7xa7x91xe5xadxa6xe7xa0x94xe7xa9xb6xe5x91x98xe4xbaxa6xe5xbax84xe6x9cxbaxe6x88xbf","address":"xe5x8cx97xe4xbaxacxe4xbaxa6xe5xbax84xe7xbbx8fxe6xb5x8exe5xbcx80xe5x8fx91xe5x8cxbaxe8x8dxa3xe5x8dx8exe5x8dx97xe8xb7xaf11xe5x8fxb7","phone":"010-53897343","email":"yinzhengjie@mail.caiq.org.cn","letter":"yz"}'
    >>> 
    >>> res = jr.render(serializer.data)
    >>> 
    使用rest_framework 自带的模块进行序列化操作(强烈推荐使用,因为它包含了异常处理!) 

    三.反序列化模型

    1>.在idcs的apps中创建序列化文件,并编写序列化代码,如下图所示

    # !/usr/bin/env python
    # _*_conding:utf-8_*_
    # @author :yinzhengjie
    # blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    
    
    
    from rest_framework import serializers
    
    
    class IdcSerializer(serializers.Serializer):
        """
            IDC序列化类
        """
        id          = serializers.IntegerField(read_only=True)                          #把当前字段设置为只读属性,如果给改字段穿参数会被忽略!
        name        = serializers.CharField(required=True,max_length=32,min_length=2)   #我们要求用户必须对改字段传参数,而且传参数对长度必须在2~32个字符之间!下面字段中对属性同理!
        address     = serializers.CharField(required=True,max_length=256)
        phone       = serializers.CharField(required=True,max_length=15)
        email       = serializers.EmailField(required=True)
        letter      = serializers.CharField(required=True,max_length=5)
    具体代码戳这里

    2>.反序列化操作 

    >>> res = jr.render(serializer.data)
    >>> 
    >>> res
    b'{"id":1,"name":"xe4xb8xadxe5x9bxbdxe6xa3x80xe9xaax8cxe6xa3x80xe7x96xabxe7xa7x91xe5xadxa6xe7xa0x94xe7xa9xb6xe5x91x98xe4xbaxa6xe5xbax84xe6x9cxbaxe6x88xbf","address":"xe5x8cx97xe4xbaxacxe4xbaxa6xe5xbax84xe7xbbx8fxe6xb5x8exe5xbcx80xe5x8fx91xe5x8cxbaxe8x8dxa3xe5x8dx8exe5x8dx97xe8xb7xaf11xe5x8fxb7","phone":"010-53897343","email":"yinzhengjie@mail.caiq.org.cn","letter":"yz"}'
    >>> 
    >>> 
    >>> from django.utils.six import BytesIO
    >>> 
    >>> stream = BytesIO(res)
    >>> 
    >>> stream.read()
    b'{"id":1,"name":"xe4xb8xadxe5x9bxbdxe6xa3x80xe9xaax8cxe6xa3x80xe7x96xabxe7xa7x91xe5xadxa6xe7xa0x94xe7xa9xb6xe5x91x98xe4xbaxa6xe5xbax84xe6x9cxbaxe6x88xbf","address":"xe5x8cx97xe4xbaxacxe4xbaxa6xe5xbax84xe7xbbx8fxe6xb5x8exe5xbcx80xe5x8fx91xe5x8cxbaxe8x8dxa3xe5x8dx8exe5x8dx97xe8xb7xaf11xe5x8fxb7","phone":"010-53897343","email":"yinzhengjie@mail.caiq.org.cn","letter":"yz"}'
    >>> 
    读取流中的数据
    >>> jr.render(serializer.data)
    b'{"id":1,"name":"xe4xb8xadxe5x9bxbdxe6xa3x80xe9xaax8cxe6xa3x80xe7x96xabxe7xa7x91xe5xadxa6xe7xa0x94xe7xa9xb6xe5x91x98xe4xbaxa6xe5xbax84xe6x9cxbaxe6x88xbf","address":"xe5x8cx97xe4xbaxacxe4xbaxa6xe5xbax84xe7xbbx8fxe6xb5x8exe5xbcx80xe5x8fx91xe5x8cxbaxe8x8dxa3xe5x8dx8exe5x8dx97xe8xb7xaf11xe5x8fxb7","phone":"010-53897343","email":"yinzhengjie@mail.caiq.org.cn","letter":"yz"}'
    >>> 
    >>> res = jr.render(serializer.data)
    >>> 
    >>> from django.utils.six import BytesIO
    >>> 
    >>> stream = BytesIO(res)
    >>> 
    >>> from rest_framework.parsers import JSONParser
    >>> 
    >>> jsondata = JSONParser()
    >>> 
    >>> data = jsondata.parse(stream)
    >>> 
    >>> data
    {'id': 1, 'name': '中国检验检疫科学研究员亦庄机房', 'address': '北京亦庄经济开发区荣华南路11号', 'phone': '010-53897343', 'email': 'yinzhengjie@mail.caiq.org.cn', 'letter': 'yz'}
    >>> 
    >>> 
    使用rest_framework模块进行反序列化操作
    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py  shell
    Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 26 2018, 19:50:54) 
    [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> 
    >>> data = {'id': 1, 'name': '中国检验检疫科学研究员亦庄机房', 'address': '北京亦庄经济开发区荣华南路11号', 'phone': '010-53897343', 'email': 'yinzhengjie@mail.caiq.org.cn', 'letter': 'yz'}
    >>> 
    >>> from idcs.serializers import IdcSerializer      
    >>> 
    >>> serializer = IdcSerializer(data=data)
    >>> 
    >>> serializer
    IdcSerializer(data={'id': 1, 'name': '中国检验检疫科学研究员亦庄机房', 'address': '北京亦庄经济开发区荣华南路11号', 'phone': '010-53897343', 'email': 'yinzhengjie@mail.caiq.org.cn', 'letter': 'yz'}):
        id = IntegerField(read_only=True)
        name = CharField(max_length=32, min_length=2, required=True)
        address = CharField(max_length=256, required=True)
        phone = CharField(max_length=15, required=True)
        email = EmailField(required=True)
        letter = CharField(max_length=5, required=True)
    >>> 
    >>> 
    >>> serializer.is_valid()          #验证成功返回True
    True
    >>>
    >>> serializer.validated_data             #获取到所有干净的数据,
    OrderedDict([('name', '中国检验检疫科学研究员亦庄机房'), ('address', '北京亦庄经济开发区荣华南路11号'), ('phone', '010-53897343'), ('email', 'yinzhengjie@mail.caiq.org.cn'), ('letter', 'yz')])
    >>> 
    使用自定义类反序列化并严重是否成功案例!

    四.调用save方法

    1>.在idcs的apps中创建序列化文件,并编写序列化代码,如下图所示

    # !/usr/bin/env python
    # _*_conding:utf-8_*_
    # @author :yinzhengjie
    # blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    
    
    
    from rest_framework import serializers
    from .models import Idc
    
    
    class IdcSerializer(serializers.Serializer):
        """
            IDC序列化类
        """
        id          = serializers.IntegerField(read_only=True)                          #把当前字段设置为只读属性,如果给改字段穿参数会被忽略!
        name        = serializers.CharField(required=True,max_length=32,min_length=2)   #我们要求用户必须对改字段传参数,而且传参数对长度必须在2~32个字符之间!下面字段中对属性同理!
        address     = serializers.CharField(required=True,max_length=256)
        phone       = serializers.CharField(required=True,max_length=15)
        email       = serializers.EmailField(required=True)
        letter      = serializers.CharField(required=True,max_length=5)
    
        def create(self, validated_data):
            return Idc.objects.create(**validated_data)
    
        def update(self, instance, validated_data):
            instance.name = validated_data.get("name",instance.name)
            instance.address = validated_data.get("name", instance.address)
            instance.phone = validated_data.get("name", instance.phone)
            instance.email = validated_data.get("name", instance.email)
            instance.save()                     #这里这里的save方法会把数据写入到数据库中!
            return instance
    具体代码戳这里!

     

    2>.调用save方法

    (venv) bogon:yinzhengjie_devops yinzhengjie$ python manage.py  shell
    Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 26 2018, 19:50:54) 
    [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> 
    >>> data = {'name': '中国检验检疫科学研究员亦庄机房', 'address': '北京亦庄经济开发区荣华南路11号', 'phone': '010-53897343', 'email': 'yinzhengjie@mail.caiq.org.cn', 'letter': 'yz'})
      File "<console>", line 1
        data = {'name': '中国检验检疫科学研究员亦庄机房', 'address': '北京亦庄经济开发区荣华南路11号', 'phone': '010-53897343', 'email': 'yinzhengjie@mail.caiq.org.cn', 'letter': 'yz'})
                                                                                                                                                           ^
    SyntaxError: invalid syntax
    >>> 
    >>> 
    >>> 
    >>> data = {'name': '中国检验检疫科学研究员亦庄机房', 'address': '北京亦庄经济开发区荣华南路11号', 'phone': '010-53897343', 'email': 'yinzhengjie@mail.caiq.org.cn', 'letter': 'yz'}
    >>> 
    >>> from idcs.serializers import IdcSerializer
    >>> 
    >>> serializer = IdcSerializer(data=data)
    >>> 
    >>> serializer.is_valid()
    True
    >>> 
    >>> serializer.save()          #只要调用save方法,默认就会去调用序列化类的create方法,这是因为django它有判断机制,如果你没有给它传递id字段就以为你是创建(create),如果有id字段就以为你要做更新操作(updata)
    <Idc: 中国检验检疫科学研究员亦庄机房>
    >>> 
    >>> 

    >>> from idcs.models import Idc
    >>>
    >>> Idc.objects.all()                        #验证是否保存成功,我们可以查看此时数据库的数据,很显然由2条数据变为3条数据,说明保存成功啦!
    <QuerySet [<Idc: 中国检验检疫科学研究员亦庄机房>, <Idc: 中国检验检疫科学研究院高碑店机房>, <Idc: 中国检验检疫科学研究员亦庄机房>]>
    >>>
    >>> data = IdcSerializer(Idc.objects.all(),many=True)     #序列化多条数据!
    >>>

    >>> from rest_framework.renderers import JSONRenderer
    >>>
    >>> res = JSONRenderer().render(data.data)           #将多条数据取出来~
    >>>
    >>> res
    b'[{"id":1,"name":"xe4xb8xadxe5x9bxbdxe6xa3x80xe9xaax8cxe6xa3x80xe7x96xabxe7xa7x91xe5xadxa6xe7xa0x94xe7xa9xb6xe5x91x98xe4xbaxa6xe5xbax84xe6x9cxbaxe6x88xbf","address":"xe5x8cx97xe4xbaxacxe4xbaxa6xe5xbax84xe7xbbx8fxe6xb5x8exe5xbcx80xe5x8fx91xe5x8cxbaxe8x8dxa3xe5x8dx8exe5x8dx97xe8xb7xaf11xe5x8fxb7","phone":"010-53897343","email":"yinzhengjie@mail.caiq.org.cn","letter":"yz"},{"id":2,"name":"xe4xb8xadxe5x9bxbdxe6xa3x80xe9xaax8cxe6xa3x80xe7x96xabxe7xa7x91xe5xadxa6xe7xa0x94xe7xa9xb6xe9x99xa2xe9xabx98xe7xa2x91xe5xbax97xe6x9cxbaxe6x88xbf","address":"xe9xabx98xe7xa2x91xe5xbax97","phone":"010-53897343","email":"jky@mail.caiq.org.cn","letter":"gbd"},{"id":3,"name":"xe4xb8xadxe5x9bxbdxe6xa3x80xe9xaax8cxe6xa3x80xe7x96xabxe7xa7x91xe5xadxa6xe7xa0x94xe7xa9xb6xe5x91x98xe4xbaxa6xe5xbax84xe6x9cxbaxe6x88xbf","address":"xe5x8cx97xe4xbaxacxe4xbaxa6xe5xbax84xe7xbbx8fxe6xb5x8exe5xbcx80xe5x8fx91xe5x8cxbaxe8x8dxa3xe5x8dx8exe5x8dx97xe8xb7xaf11xe5x8fxb7","phone":"010-53897343","email":"yinzhengjie@mail.caiq.org.cn","letter":"yz"}]'
    >>>
    >>>

    五.总结

    1>.序列化

      1.1>.拿到queryset

      1.2>.将queryset给序列化类

          serializer = IdcSerializer(idc)          #序列化一条数据
    
          serializer = IdcSerializer(idc,many=True)    #序列化多条数据

      1.3>.转JSON格式

        JSONRenderer().render(serializer.data)

    2>.反序列化

      from rest_framework.parses import JSONParser
    
      data = JSONParser().parse(BytesIO(content))
      serializer = IdcSerializer(data=data)
    
      serializer.is_valid()
    
      serializer.save()
  • 相关阅读:
    斐波那契数列
    MySQL
    GIT
    shell执行Python并传参
    摘选改善Python程序的91个建议2
    摘选改善Python程序的91个建议
    django执行原生sql
    admin
    分支&循环
    git
  • 原文地址:https://www.cnblogs.com/yinzhengjie/p/10287458.html
Copyright © 2020-2023  润新知