• django-rest-framework登陆认证


    # -*- coding: utf-8 -*-
    __author__ = 'YongCong Wu'
    # @Time    : 2018/10/23 15:05
    # @Email   :  : 1922878025@qq.com
    from rest_framework import exceptions
    from app import models
    
    
    class FirstAuthtication(object):
        def authenticate(self, request):
            pass
    
        def authenticate_header(self, request):
            pass
    
    
    class Authtication(object):
        def authenticate(self, request):
            token = request._request.GET.get('token')
            token_obj = models.UserToken.objects.filter(token=token).first()
            if not token_obj:
                raise exceptions.AuthenticationFailed('用户认证失败')
            # 在rest framework内部将整个两个字段赋值给request,以供后续操作使用。
            return (token_obj.user, token_obj)
    
        def authenticate_header(self, request):
            pass
    auth.py
    from django.shortcuts import render, HttpResponse
    from django.contrib.auth.models import User, Group
    from rest_framework import viewsets
    from app.serializers import UserSerializer, GroupSerializer
    from rest_framework.views import APIView
    from rest_framework.request import Request
    from rest_framework.authentication import BasicAuthentication
    from rest_framework import exceptions
    from django.http import JsonResponse
    from app import models
    import hashlib
    import time
    
    # 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
    
    # 生成md5
    def md5(user):
        ctime = str(time.time())
        m = hashlib.md5(bytes(user, encoding='utf-8'))
        m.update(bytes(ctime, encoding='utf-8'))
        return m.hexdigest()
    
    
    # 请求Token认证
    class GetUserData(APIView):
        """
        用于用户登陆认证
        """
        authentication_classes = []
        def post(self, request, *args, **kwargs):
            ret = {'code': 1000, 'msg': None}
            try:
                user = request._request.POST.get('username')
                pwd = request._request.POST.get('password')
                obj = models.UserInfo.objects.filter(username=user, password=pwd).first()
                if not obj:
                    ret['code'] = 1001
                    ret['msg'] = '用户名或密码错误'
                # 为当前登陆用户创建Token
                token = md5(user)
                models.UserToken.objects.update_or_create(user=obj, defaults={'token':token})
                ret['token'] = token
            except Exception as e:
                ret['code'] = 1002
                ret['msg'] = '请求异常'
            return JsonResponse(ret)
    
    
    
    # 测试数据
    ORDER_DICT = {
        1: {
            'name': '书包',
            'sku': 1002,
            'price': 500
        },
        2: {
            'name': '键盘',
            'sku': 1052,
            'price': 258
        }
    }
    
    class OrderView(APIView):
        """
        用于订单    rest framework
        """
        # 通过authentication_classes添加用户认证
        def get(self, request, *args, **kwargs):
            """
            用户登陆成功,才可以查看订单数据
            """
            ret = {'code': 1000, 'msg': None, 'data': None}
            try:
                ret['data'] = ORDER_DICT
            except Exception as e:
                pass
            return JsonResponse(ret)
    
    # 用户中心
    class UserInfoView(APIView):
        """
        用于订单    rest framework
        """
        # 通过authentication_classes添加用户认证
        def get(self, request, *args, **kwargs):
            return HttpResponse('用户信息')
    app/views.py
    from django.db import models
    
    # Create your models here.
    
    
    class UserInfo(models.Model):
        user_type_choices = (
            (1, '普通用户'),
            (2, 'VIP'),
            (3, 'SVIP')
        )
        user_type = models.IntegerField(choices=user_type_choices)
        username = models.CharField(max_length=32, unique=True)
        password = models.CharField(max_length=64)
    
    
    class UserToken(models.Model):
        user = models.OneToOneField(to='UserInfo')
        token = models.CharField(max_length=64)
    models
    # -*- coding:utf-8 -*-
    
    
    from django.conf.urls import url, include
    from rest_framework import routers
    from app import views
    
    
    
    # 注册视图
    router = routers.DefaultRouter()
    router.register(r'users', views.UserViewSet)
    router.register(r'groups', views.GroupViewSet)
    router.register(r'pwd', views.GroupViewSet)
    
    
    
    # 二级路由
    urlpatterns = [
        url(r'apb/',include(router.urls)),
        url(r'1/',include(router.urls)),
        url(r'auth/$', views.GetUserData.as_view()),            # 登陆认证
        url(r'order/$', views.OrderView.as_view())               # 订单
    ]
    app/urls.py
    from django.conf.urls import url, include
    from django.contrib import admin
    from rest_framework import routers, serializers, viewsets
    from app import views
    
    
    # django-rest-swagger
    from rest_framework.schemas import get_schema_view
    from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer
    schema_view = get_schema_view(title='User API', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])
    
    
    urlpatterns = [
        url(r'^docs/', schema_view, name='docs'),
        url(r'^admin/', admin.site.urls),
        url(r'^api', include('rest_framework.urls', namespace='rest_framework')),
        url(r'^user/', include('app.urls'))
    rest_frame_demo/urls.py

    settings.py配置全局认证

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': ['app.utils.auth.FirstAuthtication', 'app.utils.auth.Authtication']
    }
    settings.py

    django-rest-swagger配置

    # Swagger样式配置
    SWAGGER_SETTINGS = {
        'SECURITY_DEFINITIONS': {
            'basic': {
                'type': 'basic'
            }
        },
        'LOGIN_URL': 'rest_framework:login',
        'LOGOUT_URL': 'rest_framework:logout',
        # 接口文档中方法列表以首字母升序排列
        'APIS_SORTER': 'alpha',
        # 如果支持json提交,则接口文档中包含json输入框
        'JSON_EDITOR': True,
        # 方法列表字母排序
        'OPERTIONS_SORTER': 'alpha',
        'VALIDATOR_URL': None
    }
    settings.py

    app/serializers.py

    # -*- coding:utf-8 -*-
    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')
    serializers.py
  • 相关阅读:
    个人总结一些常见的css问题
    工作中的js总结
    js面向对象
    js的一些特性
    js 实现改变字体大小
    将博客搬至CSDN
    最大连续子序列----DP动态规划
    捡石子---贪心算法(huffman)
    素数环问题---深度搜索遍历
    nyoj---12 喷水装置(二)--区间覆盖问题
  • 原文地址:https://www.cnblogs.com/wuyongcong/p/9836981.html
Copyright © 2020-2023  润新知