zoukankan      html  css  js  c++  java
  • Django REST framework(序列化)

    准备工作

    一丶配置虚拟环境

    1.安装虚拟包:pip install virtualenv 

    2.创建一个用于虚拟环境的目录,并进入到目录下

    3.执行 python -m venv 虚拟环境名

    4.执行 virtualenv 虚拟环境名

    5.在目录下激活虚拟环境  

    windos下:source envScriptsactivate

    linux下:source env/bin/activate

    6.停止虚拟环境 deactivate指令或者关闭终端

    二丶用于代码高亮显示pip install pygments

    开始

    一丶创建一个项目

    1.新建一个项目目录,在目录中创建一个Django项目

    cd 项目目标目录
    django-admin.py startproject 项目名
    cd 项目目录下
    

    2.创建一个Django应用

    python manage.py startapp snippets
    

    3.将rest_framework和新建的应用注册到settings.py的INSTALLED_APPS中

    INSTALLED_APPS = (
        ...
        'rest_framework',
        'snippets.apps.SnippetsConfig',
    )
    

    二丶编辑模型层

    1.编辑模型层文件

    应用下的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',)
    

    2.迁移数据

    项目根目录下
    python manage.py makemigrations 应用名
    python manage.py migrate
    

    三丶序列化

    1.应用下建立serializers.py文件

    from rest_framework import serializers
    from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
    
    
    class SnippetSerializer(serializers.Serializer):
        id = 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):
            """
            Create and return a new `Snippet` instance, given the validated data.
            """
            return Snippet.objects.create(**validated_data)
    
        def update(self, instance, validated_data):
            """
            Update and return an existing `Snippet` instance, given the 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
    

    四丶使用序列化器

    一丶序列化

    1.进入python shell:python manage.py shell

    from snippets.models import Snippet
    from snippets.serializers import SnippetSerializer
    from rest_framework.renderers import JSONRenderer
    from rest_framework.parsers import JSONParser
    
    snippet = Snippet(code='foo = "bar"
    ')
    snippet.save()
    
    snippet = Snippet(code='print "hello, world"
    ')
    snippet.save()
    

    2.查看实例化的数据

    serializer = SnippetSerializer(snippet)
    serializer.data
    # {'id': 2, 'title': u'', 'code': u'print "hello, world"
    ', 'linenos': False, 'language': u'python', 'style': u'friendly'}

    3.转换为json数据

    content = JSONRenderer().render(serializer.data)
    content
    # '{"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}'
    

    二丶反序列化

    1.解析字符串为python原生的数据类型

    from django.utils.six import BytesIO
    
    stream = BytesIO(content)
    data = JSONParser().parse(stream)
    

    2.将原生数据类型变为对象实例

    serializer = SnippetSerializer(data=data)
    serializer.is_valid()
    # True
    serializer.validated_data
    # OrderedDict([('title', ''), ('code', 'print "hello, world"
    '), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
    serializer.save()
    # <Snippet: Snippet object>
    

    3.序列化querysets实例,将many=True参数加入序列化器

    serializer = SnippetSerializer(Snippet.objects.all(), many=True)
    serializer.data
    # [OrderedDict([('id', 1), ('title', u''), ('code', u'foo = "bar"
    '), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', u''), ('code', u'print "hello, world"
    '), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', u''), ('code', u'print "hello, world"'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]
    

    五丶使用ModelSerializers

    REST framework包括Serializer类和ModelSerializer类,这样可以使代码更加的整洁.

    ModelSerializer就像是Django的表单,不会有特别的功能但是是序列化的一个快捷方式.

    1.找到应用下的serializers.py文件,替换代码

    class SnippetSerializer(serializers.ModelSerializer):
        class Meta:
            model = Snippet
            fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
    

    2.查看序列化器的所有字段

    from snippets.serializers import SnippetSerializer
    serializer = SnippetSerializer()
    print(repr(serializer))
    # SnippetSerializer():
    #    id = IntegerField(label='ID', read_only=True)
    #    title = CharField(allow_blank=True, max_length=100, required=False)
    #    code = CharField(style={'base_template': 'textarea.html'})
    #    linenos = BooleanField(required=False)
    #    language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...
    #    style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...
    

    六丶编写序列化试图

    1.编辑应用下的views.py文件

    from django.http import HttpResponse, JsonResponse
    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

    2.加入以下方法

    @csrf_exempt
    def snippet_list(request):
        """
        List all code snippets, or create a new snippet.
        """
        if request.method == 'GET':
            snippets = Snippet.objects.all()
            serializer = SnippetSerializer(snippets, many=True)
            return JsonResponse(serializer.data, safe=False)
    
        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)

    3.上述代码的升级版,用于增删改查数据

    @csrf_exempt #跨越csrf令牌,进行POST请求
    def snippet_detail(request, pk):
        """
        Retrieve, update or delete a code snippet.
        """
        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)
    

    4.url设置

    创建应用的urls.py文件
    from django.conf.urls import url
    from snippets import views
    
    urlpatterns = [
        url(r'^snippets/$', views.snippet_list),
        url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),
    ]
    项目的urls.py文件
    
    from django.conf.urls import url, include
    
    urlpatterns = [
        url(r'^', include('snippets.urls')),
    ]
    

    七丶测试Web API

    1.运行Django服务:python manage.py runserver

    2.安装httpie:pip install httpie,这是一个http客户端用python编写对客户非常友好

    3.得到所有的数据列表

    http http://127.0.0.1:8000/snippets/
    
    HTTP/1.1 200 OK
    ...
    [
      {
        "id": 1,
        "title": "",
        "code": "foo = "bar"
    ",
        "linenos": false,
        "language": "python",
        "style": "friendly"
      },
      {
        "id": 2,
        "title": "",
        "code": "print "hello, world"
    ",
        "linenos": false,
        "language": "python",
        "style": "friendly"
      }
    ]
    

    4.通过id得到列表

    http http://127.0.0.1:8000/snippets/2/
    
    HTTP/1.1 200 OK
    ...
    {
      "id": 2,
      "title": "",
      "code": "print "hello, world"
    ",
      "linenos": false,
      "language": "python",
      "style": "friendly"
    }
    

    5.也可以通过浏览器来访问Django项目 

      

     

     

      

      

     

  • 相关阅读:
    C#读取并修改app.congig的实例
    apache:添加cgi模式
    初识golang
    Golang: pprof
    Golang:测试map是否存在
    beego: 获取request参数
    shell:crontab
    初识Iaas,paas
    初识golang
    Go-new和make
  • 原文地址:https://www.cnblogs.com/cangshuchirou/p/9264909.html
Copyright © 2011-2022 走看看