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


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

                                     作者:尹正杰

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

    一.案例一

    1>.目录结构如下图所示

    2>.各个文件代码如下所示

    """yinzhengjie_devops URL Configuration
    
    The `urlpatterns` list routes URLs to views. For more information please see:
        https://docs.djangoproject.com/en/2.1/topics/http/urls/
    Examples:
    Function views
        1. Add an import:  from my_app import views
        2. Add a URL to urlpatterns:  path('', views.home, name='home')
    Class-based views
        1. Add an import:  from other_app.views import Home
        2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
    Including another URLconf
        1. Import the include() function: from django.urls import include, path
        2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
    """
    from django.conf.urls import url,include
    from django.contrib import admin
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r"^",include("idcs.urls"))
    ]
    根的ursl 文件内容
    # !/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 django.conf.urls import url
    from .views import idc_list
    
    urlpatterns = [
        url("^idcs/$",idc_list)
    ]
    idcs.urls 文件内容
    # !/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 django.shortcuts import render
    
    from  django.http import HttpResponse
    from  .models import Idc
    from  .serializers import IdcSerializer
    from rest_framework.renderers import JSONRenderer
    from  rest_framework.parsers import JSONParser
    
    
    
    
    def idc_list(request,*args,**kwargs):
       if request.method == "GET":
            #从数据库查询所有的数据
            queryset    = Idc.objects.all()
            #将查询的结果进行序列化操作,因为查询的结果有多条数据,因此我们需要加一个"many=True"属性,表示序列化查询出来的所有数据
            serializer  = IdcSerializer(queryset,many=True)
            #将数据转换成JSON格式的字符串
            content = JSONRenderer().render(serializer.data)
            return HttpResponse(content,content_type="application/json")
    
       elif request.method == "POST":
           #解析字符串
           data = JSONParser().parse(request)
           #将字符串进行序列化操作并判断序列化后 数据是否有效,如果有效就写入数据库!
           serializer = IdcSerializer(data=data)
           if serializer.is_valid():
               serializer.save()
               content = JSONRenderer().render(serializer.data)
               return HttpResponse(content, content_type="application/json")
       return HttpResponse("尹正杰到此一游!")
    idcs.views 文件内容
    # !/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 django.shortcuts import render
    
    from  django.http import HttpResponse
    from  .models import Idc
    from  .serializers import IdcSerializer
    from rest_framework.renderers import JSONRenderer
    from  rest_framework.parsers import JSONParser
    
    
    
    
    def idc_list(request,*args,**kwargs):
       if request.method == "GET":
            #从数据库查询所有的数据
            queryset    = Idc.objects.all()
            #将查询的结果进行序列化操作,因为查询的结果有多条数据,因此我们需要加一个"many=True"属性,表示序列化查询出来的所有数据
            serializer  = IdcSerializer(queryset,many=True)
            #将数据转换成JSON格式的字符串
            content = JSONRenderer().render(serializer.data)
            return HttpResponse(content,content_type="application/json")
    
       elif request.method == "POST":
           #解析字符串
           data = JSONParser().parse(request)
           #将字符串进行序列化操作并判断序列化后 数据是否有效,如果有效就写入数据库!
           serializer = IdcSerializer(data=data)
           if serializer.is_valid():
               serializer.save()
               content = JSONRenderer().render(serializer.data)
               return HttpResponse(content, content_type="application/json")
       return HttpResponse("尹正杰到此一游!")
    
    
    def idc_detail(request,pk,*args,**kwargs):
       try:
           # 获取某个主键的ID,获取一条数据
           idc = Idc.objects.get(pk=pk)
       except Idc.DoesNotExist:
           return HttpResponse(status=404)
    
       if request.method == "GET":
           serializer = IdcSerializer(idc)
           content = JSONRenderer().render(serializer.data)
           return HttpResponse(content, content_type="application/json")
    
       elif request.method == "POST":
           content = JSONParser().parse(request)
           serializer = IdcSerializer(data=content)
           if serializer.is_valid():
               serializer.save()
               content = JSONRenderer().render(serializer.data)
               return HttpResponse(content, content_type="application/json")
    idcs.serializers 文件内容

    3>.web端访问

     4>.服务端访问日志

    二.案例二

    1>.目录结构如下图所示

    2>.各个文件代码如下

    """yinzhengjie_devops URL Configuration
    
    The `urlpatterns` list routes URLs to views. For more information please see:
        https://docs.djangoproject.com/en/2.1/topics/http/urls/
    Examples:
    Function views
        1. Add an import:  from my_app import views
        2. Add a URL to urlpatterns:  path('', views.home, name='home')
    Class-based views
        1. Add an import:  from other_app.views import Home
        2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
    Including another URLconf
        1. Import the include() function: from django.urls import include, path
        2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
    """
    from django.conf.urls import url,include
    from django.contrib import admin
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r"^",include("idcs.urls"))
    ]
    根的ursl 文件内容
    # !/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 django.conf.urls import url
    from .views import idc_list,idc_detail
    
    urlpatterns = [
        url("^idcs/$",idc_list),
        #下面的?P表示需要传递一个参数,而<pk>表示是给参数P起了一个名称,后面的[0-9]+正则表示改值的取值范围。
        url("^idcs/(?P<pk>[0-9]+)/$", idc_detail)
    ]
    idcs.urls 文件内容
    # !/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 django.shortcuts import render
    
    from  django.http import HttpResponse,JsonResponse
    from  .models import Idc
    from  .serializers import IdcSerializer
    from rest_framework.renderers import JSONRenderer
    from  rest_framework.parsers import JSONParser
    
    
    
    
    def idc_list(request,*args,**kwargs):
       if request.method == "GET":
            #从数据库查询所有的数据
            queryset    = Idc.objects.all()
            #将查询的结果进行序列化操作,因为查询的结果有多条数据,因此我们需要加一个"many=True"属性,表示序列化查询出来的所有数据
            serializer  = IdcSerializer(queryset,many=True)
            #将数据转换成JSON格式的字符串
            content = JSONRenderer().render(serializer.data)
            return HttpResponse(content,content_type="application/json")
    
       elif request.method == "POST":
           #解析字符串
           data = JSONParser().parse(request)
           #将字符串进行序列化操作并判断序列化后 数据是否有效,如果有效就写入数据库!
           serializer = IdcSerializer(data=data)
           if serializer.is_valid():
               serializer.save()
               content = JSONRenderer().render(serializer.data)
               return HttpResponse(content, content_type="application/json")
       return HttpResponse("尹正杰到此一游!")
    
    
    def idc_detail(request,pk,*args,**kwargs):
       try:
           # 获取某个主键的ID,获取一条数据
           idc = Idc.objects.get(pk=pk)
       except Idc.DoesNotExist:
           return HttpResponse(status=404)
    
       if request.method == "GET":
           serializer = IdcSerializer(idc)
           content = JSONRenderer().render(serializer.data)
           return HttpResponse(content, content_type="application/json")
    
       elif request.method == "POST":
           data = JSONParser().parse(request)
           serializer = IdcSerializer(data=data)
           if serializer.is_valid():
               serializer.save()
               content = JSONRenderer().render(serializer.data)
               return HttpResponse(content, content_type="application/json")
           return JsonResponse(serializer.errors,status=400)
    
       elif request.method == "DELETE":
           idc.delete()
           #给前端返回空数据
           return HttpResponse(status=204)
    idcs.views 文件内容
    # !/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 django.db import models
    
    
    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"
    idcs.moudels 文件内容
    # !/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("address", instance.address)
            instance.phone = validated_data.get("phone", instance.phone)
            instance.email = validated_data.get("email", instance.email)
            instance.save()                                                              #这里这里的save方法会把数据写入到数据库中!
            return instance
    idcs.serializers 文件内容

    3>.启动项目后,模拟浏览器访问服务,获取相应的数据信息

    bogon:~ yinzhengjie$ http  http://127.0.0.1:8000/idcs/3/
    HTTP/1.0 200 OK
    Content-Length: 196
    Content-Type: application/json
    Date: Thu, 28 Feb 2019 09:13:58 GMT
    Server: WSGIServer/0.2 CPython/3.6.6
    X-Frame-Options: SAMEORIGIN
    
    {
        "address": "北京亦庄经济开发区荣华南路11号",
        "email": "yinzhengjie@mail.caiq.org.cn",
        "id": 3,
        "letter": "yz",
        "name": "中国检验检疫科学研究员亦庄机房",
        "phone": "010-53897343"
    }
    
    bogon:~ yinzhengjie$ 
    bogon:~ yinzhengjie$ 
    bogon:~ yinzhengjie$ http  http://127.0.0.1:8000/idcs/2/
    HTTP/1.0 200 OK
    Content-Length: 157
    Content-Type: application/json
    Date: Thu, 28 Feb 2019 09:14:02 GMT
    Server: WSGIServer/0.2 CPython/3.6.6
    X-Frame-Options: SAMEORIGIN
    
    {
        "address": "高碑店",
        "email": "jky@mail.caiq.org.cn",
        "id": 2,
        "letter": "gbd",
        "name": "中国检验检疫科学研究院高碑店机房",
        "phone": "010-53897343"
    }
    
    bogon:~ yinzhengjie$ 
    bogon:~ yinzhengjie$ http  http://127.0.0.1:8000/idcs/1/
    HTTP/1.0 200 OK
    Content-Length: 196
    Content-Type: application/json
    Date: Thu, 28 Feb 2019 09:14:06 GMT
    Server: WSGIServer/0.2 CPython/3.6.6
    X-Frame-Options: SAMEORIGIN
    
    {
        "address": "北京亦庄经济开发区荣华南路11号",
        "email": "yinzhengjie@mail.caiq.org.cn",
        "id": 1,
        "letter": "yz",
        "name": "中国检验检疫科学研究员亦庄机房",
        "phone": "010-53897343"
    }
    
    bogon:~ yinzhengjie$ 
  • 相关阅读:
    php header 跳转 ie问题
    Filter过滤不了Action的问题
    DB2中sql语句占位符问题
    LL(1)文法
    算法分析实验报告词法分析器
    大数据概述
    2016.9.30 编译原理词法分析器
    131有确定性的有穷自动机
    Python基础综合练习
    组合数据类型练习
  • 原文地址:https://www.cnblogs.com/yinzhengjie/p/10447583.html
Copyright © 2020-2023  润新知