• (一)rest_framework初探


    一、前期环境准备

    • 安装python虚拟环境(也可以不安装,个人喜好)
    • python3.6
    • djangorestframework:3.10.2
    • djangorestframework-jwt:1.11.0
    • coreapi:2.3.3
    # 创建虚拟python虚拟环境
    [root@vm10-0-1-23 ~]# mkvirtualenv rest_framework
    (rest_framework) [root@vm10-0-1-23 ~]# pip install django
    (rest_framework) [root@vm10-0-1-23 ~]# pip install djangorestframework
    (rest_framework) [root@vm10-0-1-23 ~]# pip install djangorestframework-jwt
    (rest_framework) [root@vm10-0-1-23 ~]# pip install coreapi
    (rest_framework) [root@vm10-0-1-23 ~]# pip install markdown
    (rest_framework) [root@vm10-0-1-23 ~]# pip install django-filter
    

    django环境可以通过pycharm之类的IDE进行创建即可,具体可以参考该文档

    # 添加'rest_framework'到您的INSTALLED_APPS设置
    INSTALLED_APPS = [
        ...
        'rest_framework',
    ]
    

    二、配置url和settings文件

    url.py

    from django.conf.urls import url, include
    from django.contrib import admin
    from rest_framework.documentation import include_docs_urls
    from rest_framework.routers import DefaultRouter
    from rest_framework_jwt.views import obtain_jwt_token
    from rest_framework.authtoken import views
    
    
    router = DefaultRouter()
    # router.register()
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
        url(r'^api-token-auth/', views.obtain_auth_token),
        url(r'^', include(router.urls)),
        # rest_framework提供api文档服务
        url(r'docs/', include_docs_urls(title='restful')),
        url(r'^login/', obtain_jwt_token),
    
    
    ]  

    settings.py

    # drf的token登陆
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.BasicAuthentication',
            'rest_framework.authentication.SessionAuthentication',
    
        ),
        # 如果djangorestframework版本是3.6以前的,则这一行不需要,之后的版本如果不加会出现'AutoSchema' object has no attribute 'get_link'错误
        # 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema'
    }
    
    import datetime
    JWT_AUTH = {
        'JWT_EXPIRATION_DELTA': datetime.timedelta(days=3),
    
        'JWT_AUTH_HEADER_PREFIX': 'JWT',
    }

    完成以上操作,基本的功能就实现了,这时就可以在自己的app视图函数中写接口了

    三、写一个简单的api接口

     1.创建数据包,实现一个简单登陆注册功能

    # 在你的app model.py中写一个用户表
    from django.contrib.auth.models import AbstractUser
    from django.db import models
    
    # Create your models here.
    
    class UserProfile(AbstractUser):
        '''
        用户
        '''
        name = models.CharField(max_length=30, null=True, blank=True, verbose_name="姓名")
        birthday = models.DateField(null=True, blank=True, verbose_name="出生年月")
        gender = models.CharField(max_length=6, choices=(("male", "男"), ("female", "女")), default="female",
                                  verbose_name="性别")
        mobile = models.CharField(null=True, blank=True, max_length=11, verbose_name="电话")
        email = models.EmailField(max_length=100, null=True, blank=True, verbose_name="邮箱")
    
        class Meta:
            verbose_name = "用户"
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.username
    

    2.写一个serializers文件,其中官方给出的serializers解释如下:

    序列化器允许把像查询集和模型实例这样的复杂数据转换为可以轻松渲染成JSONXML或其他内容类型的原生Python类型。序列化器还提供反序列化,在验证传入的数据之后允许解析数据转换回复杂类型。

    REST framework中的serializers与Django的FormModelForm类非常像。我们提供了一个Serializer类,它为你提供了强大的通用方法来控制响应的输出,以及一个ModelSerializer类,它为创建用于处理模型实例和查询集的序列化程序提供了有用的快捷实现方式。

    # 在自己的app目录下创建一个serializers.py文件,和views.py同一级别
    from django.contrib.auth import get_user_model
    from rest_framework import serializers
    from rest_framework.validators import UniqueValidator
    
    
    User = get_user_model()
    
    class UserSerializers(serializers.ModelSerializer):
        username = serializers.CharField(label='用户名', help_text='用户名', required=True, allow_blank=False,
                                         validators=[UniqueValidator(queryset=User.objects.all(), message="用户已存在")]
                                         )
        password = serializers.CharField(
            style={'input_type': 'password'},
            help_text='密码',
            label='密码',
            write_only=True
        )
    
        def create(self, validated_data):
            user = super(UserSerializers, self).create(validated_data=validated_data)
            user.set_password(validated_data['password'])
            user.save()
            return user
    
        class Meta:
            model = User
            fields = ("username", "mobile", "password")
    

    3.在视图函数中写一下业务逻辑

    # views.py
    from django.contrib.auth import get_user_model
    from django.contrib.auth.backends import ModelBackend
    from django.db.models import Q
    from rest_framework import viewsets, mixins
    from rest_framework import authentication
    from rest_framework_jwt.authentication import JSONWebTokenAuthentication
    from app.serializers import UserSerializers
    from rest_framework_jwt.serializers import jwt_encode_handler, jwt_payload_handler
    from rest_framework.response import Response
    from rest_framework import status
    
    # Create your views here.
    
    User = get_user_model()
    
    
    class UserViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
        '''
        用户
        '''
        serializer_class = UserSerializers
        queryset = User.objects.all()
        authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication, )
    
        def create(self, request, *args, **kwargs):
    
            # 获取相关serializer
            serializer = self.get_serializer(data=request.data)
    
            # 进行serializer验证
            # raise_exception=True,一旦验证不通过,不再往下执行,直接引发异常
            serializer.is_valid(raise_exception=True)
            # 调用perform_create()方法,保存实例
            user = self.perform_create(serializer)
    
            re_dict = serializer.data
            payload = jwt_payload_handler(user)
            re_dict['token'] = jwt_encode_handler(payload)
            re_dict['name'] = user.name if user.name else user.username
    
            headers = self.get_success_headers(serializer.data)
            return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)
    
        def perform_create(self, serializer):
            '''
            保存实例
            :param serializer:
            :return:
            '''
            return serializer.save()
    

    4.在urls中配置路由

    # urls.py
    
    from app.views import UserViewSet
    
    
    router = DefaultRouter()
    
    router.register(r'users', UserViewSet, base_name='users')
    

    5.最后一步需要在命令行中创建一下数据表

    # 执行makemigrations和migrate命令前,需要在settings.py文件中加一下以下内容
    # app可以改成你自己程序中定义的名称,UserProfile是我定义的表明
    AUTH_USER_MODEL = 'app.UserProfile'
    
    [root@vm10-0-1-23 ~]# python manage.py makemigrations
    [root@vm10-0-1-23 ~]# python manage.py migrate

    至此就可以在命令行或者pycharm中启动自己的接口了,效果如下:

  • 相关阅读:
    【代码笔记】iOS-JQIndicatorViewDemo
    【代码笔记】iOS-plist获得城市列表
    【代码笔记】iOS-HTTPQueue下载图片
    【代码笔记】iOS-请求去掉url中的空格
    【代码笔记】iOS-collectionView实现照片删除
    【代码笔记】iOS-自定义loading(IanAlert)
    Foundation框架-NSCalendar
    iOS Xcode全面剖析
    Mac下Git的基础操作
    iOS开发UI篇—常见的项目文件介绍
  • 原文地址:https://www.cnblogs.com/watchslowly/p/11319849.html
Copyright © 2020-2023  润新知