• django rest_framework入门


    1.rest_framework的作用
    1)可以对orm和非orm资源序列化
    2)支持restful风格编程(POST,PUT,PATCH)
    3)使用类视图编写API的view,而不是函数视图,类视图更符合代码的设计模式。
    4)用户认证和权限控制

    2.使用示例
    功能如下:管理员查看,编辑用户,组信息
    1)新建名为tutorial的Project,创建一个名为quickstart的APP
    创建表,创建超级管理员

    django-admin startproject tutorial
    cd tutorial
    django-admin startapp quickstart
    python manage.py migrate
    python manage.py createsuperuser
    

    2)序列化
    创建文件/tutorial/quickstart/serializers.py编写序列化相关的代码
    所谓序列化是指将对象类型转换为json格式,反序列化是指将json格式转换为对象

    from django.contrib.auth.models import User, Group
    from rest_framework import serializers
    
    
    class UserSerializer(serializers.HyperlinkedModelSerializer):
        class Meta:
            model = User
            fields = ('url', 'username', 'email', 'groups')
    
    
    class GroupSerializer(serializers.HyperlinkedModelSerializer):
        class Meta:
            model = Group
            fields = ('url', 'name')
    

    3)Views
    视图访问层,会在url路由中注册,访问url时,会进入到响应的视图中处理响应。

    from django.shortcuts import render
    from django.contrib.auth.models import User, Group
    from rest_framework import viewsets
    from .serializers import UserSerializer, GroupSerializer
    # Create your views here.
    
    
    class UserViewSet(viewsets.ModelViewSet):
        """
        查看,编辑用户界面
        """
        queryset = User.objects.all()
        serializer_class = UserSerializer
    
    
    class GroupViewSet(viewsets.ModelViewSet):
        """
        查看,编辑组
        """
        queryset = Group.objects.all()
        serializer_class = GroupSerializer
    

    4)url注册
    编写tutorial/urls.py,注册url

    from django.conf.urls import url, include
    from django.contrib import admin
    
    from rest_framework import routers
    
    from quickstart import views
    
    router = routers.DefaultRouter()
    router.register(r'users', views.UserViewSet)
    router.register(r'groups', views.GroupViewSet)
    
    urlpatterns = [
        url(r'^', include(router.urls)),
        url(r'^admin/', admin.site.urls),
        url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
    ]
    

    使用router.register注册视图,将router.urls放入urlpatterns列表中

    5)Settings设置

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',
    ]
    
    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
        'PAGE_SIZE': 10
    }
    

    DEFAULT_PERMISSION_CLASSES:定义权限,只有管理员用户才能访问
    PAGE_SIZE:定义分页条数

    6)测试api
    启动服务

    python manage.py runserver
    

    运行结果:

    bash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/
    {
        "count": 2,
        "next": null,
        "previous": null,
        "results": [
            {
                "email": "admin@example.com",
                "groups": [],
                "url": "http://127.0.0.1:8000/users/1/",
                "username": "admin"
            },
            {
                "email": "tom@example.com",
                "groups": [                ],
                "url": "http://127.0.0.1:8000/users/2/",
                "username": "tom"
            }
        ]
    }
    

    浏览器访问,因为有了权限控制,所以要先登录

  • 相关阅读:
    解决:npm中 下载速度慢 和(无法将“nrm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确, 然后再试一次)。
    maven(一) maven到底是个啥玩意~
    Luogu3959 NOIP2017宝藏(状压dp)
    Luogu3953 NOIP2017逛公园(最短路+拓扑排序+动态规划)
    Luogu3952 NOIP2017时间复杂度
    BZOJ4753 JSOI2016最佳团体(分数规划+树形dp)
    BZOJ1975 SDOI2010魔法猪学院(启发式搜索+最短路+堆)
    BZOJ4105 THUSC2015平方运算(线段树)
    BZOJ5109 CodePlus 2017大吉大利,晚上吃鸡!(最短路+拓扑排序+bitset)
    Luogu3731 HAOI2017新型城市化(二分图匹配+强连通分量)
  • 原文地址:https://www.cnblogs.com/shijingjing07/p/9057572.html
Copyright © 2020-2023  润新知