专栏首页Python研发django-rest-framework登陆认证

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
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('用户信息')
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)
# -*- 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())               # 订单
]
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'))

settings.py配置全局认证

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

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
}

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')

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Django之Model世界

    django为使用一种新的方式,即:关系对象映射(Object Relational Mapping,简称ORM)

    Wyc
  • 初次就这么给了你(Django-rest-framework)

    工程已经创建好了,需要cd进工程里边,关键是manage.py在工程里边,我们就需要借用manage.py来进行其他的操作了。

    Wyc
  • Django之admin

     django amdin是django提供的一个后台管理页面,改管理页面提供完善的html和css,使得你在通过Model创建完数据库表之后,

    Wyc
  • Vue+Django2.0 restframework打造前后端分离的生鲜电商项目(3)

    玩蛇的胖纸
  • Vue+Django2.0 REST framework 打造前后端分离的生鲜电商项目(五)商品列表页

    玩蛇的胖纸
  • rest framework 尝鲜

    程序员同行者
  • 为控制器配置日期处理 原

    南郭先生
  • 【Mybatis】使用mybatis Interceptor对UpdateTime自动处理

    使用@Intercepts标注这是个mybatis插件,@Signature标注要拦截的操作

    周三不加班
  • 风骚的操作:区块链监控个人账户即时在线充值

    在区块链的世界里,常常很多时候用户需要充值,要不拉起钱包,要不支付到某个特定账号,这个时候可以监控合约交易记录实现实时到账,有的时候上某些网站的时候,至于是哪些...

    肉眼品世界
  • Python 之 sqlalchemy删

    py3study

扫码关注云+社区

领取腾讯云代金券