django-rest-framework(三)(认证)

本文介绍了如何在Django Rest Framework中进行认证,包括安装、简单示例、认证类的使用,以及全局认证的配置。讲解了如何在settings配置文件中设置认证,并探讨了内置的BasicAuthentication以及其他认证类。
摘要由CSDN通过智能技术生成

安装

pip install djangorestframework

认证

简单示例
from rest_framework.views import APIView
from rest_framework import exceptions


class MyAuthentication(object):
    def authenticate(self, request):
        token = request._request.GET.get('token')
        # 获取用户名和密码,然后去数据校验
        if not token:
            raise exceptions.AuthenticationFailed("用户认证失败")
        # 返回一个元组
        return ("abc", None)
    def authenticate_header(self,val):
        pass


class CrawlAll(APIView):
    
    authentication_classes = [MyAuthentication, ]
    def get(self, request, *args, **kwargs):
        # 获取abc和None
        print(request.user, request.auth)
        return HttpResponse('GET')

    def post(self, request, *args, **kwargs):
        return HttpResponse('POST')

    def put(self, request, *args, **kwargs):
        return HttpResponse('PUT')
示例项目
  • 模型
from django.db import models


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', on_delete=models.CASCADE)
    token = models.CharField(max_length=64)
  • 路由
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from api import views

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^api/v1/auth/$', views.AuthView.as_view()),
]
  • 视图
from django.http import JsonResponse
from rest_framework.views import APIView
from api.models import UserInfo, UserToken


def md5(user):
    import hashlib
    import time
    ctime = str(time.time())
    m = hashlib.md5(bytes(user, encoding='utf-8'))
    m.update(bytes(ctime, encoding='utf-8'))

    return m.hexdigest()


class AuthView(APIView):
'''用户登录成功后生成token,并保存在数据库中'''
    def post(self, request, *args, **kwargs):
        ret = {'code': 1000, 'msg': None}
        try:
            user = request._request.POST.get('username')
            password = request._request.POST.get('password')
         
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值