码迷,mamicode.com
首页 > 其他好文 > 详细

Django rest framework 之认证

时间:2020-02-25 18:26:06      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:mode   lib   用户信息   str   inf   view   object   密码   bsp   

一、基于token进行用户认证

1、settings

先将rest_framework添加到settings的app里

INSTALLED_APPS = [
    django.contrib.admin,
    django.contrib.auth,
    django.contrib.contenttypes,
    django.contrib.sessions,
    django.contrib.messages,
    django.contrib.staticfiles,
    api,   #我自己注册的APP
    rest_framework,   #添加restframework
]

 

2、url

from django.conf.urls import url
from api.apiview import apiview
urlpatterns = [    

  url(r‘^(?P<version>[v1|v2]+)/login_api/$‘, apiview.login_api.as_view()),
]
技术图片

3、models

创建两张表,一个存用户信息,一个存用户登录后的token

from django.db import models

class user_info(models.Model):
  username = models.CharField(max_length=32,unique=True,verbose_name=用户名)
  password = models.CharField(max_length=32,verbose_name=密码)
  nickname = models.CharField(max_length=32,verbose_name=昵称)

class UserToken(models.Model):
    time = models.DateTimeField(auto_now=True)
    user = models.OneToOneField(to=user_info,on_delete=None)
    token = models.CharField(max_length=64)

 

4、views

apiview.py

from django.shortcuts import HttpResponse
from utils.response import BaseResponse
from django.db import models
from api import models
import json
import time

class login_api(object):
    def post(self,request,*args,**kwargs):
        response = BaseResponse()
        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:
                response.code = 400000
                response.error = {
            ‘username‘:‘用户名或密码错误‘

          }
          response.message = ‘参数错误‘
        return HttpResponse(json.dumps(response.__dict__)) token_obj = Token() token = token_obj.CreateToken(user) models.UserToken.objects.update_or_create(user=user,defaults={token:token,time:time.time()}) response.data = { token:token, username:user, password:pwd } except Exception as e: response.error = str(e) response.code = 400001 response.message = 请求异常 return HttpResponse(json.dumps(response.__dict__))

token.py

from web import models
import time
from datetime import datetime
import hashlib

class Token(object):
    def CreateToken(self,user):
        ‘‘‘
        创建token username + 时间戳 转换为md5
        :param user:
        :return:
        ‘‘‘
        ctime = str(time.time())
        token = hashlib.md5(bytes(user, encoding=utf-8))
        token.update(bytes(ctime, encoding=utf-8))
        return token.hexdigest()

response.py

class BaseResponse(object):
    def __init__(self):
        self.message = OK!
        self.data = None
        self.error = None
        self.code = 200

 

使用postman进行测试

如果用户名和密码正确,会生成token,下次登录时,token的值会更新

技术图片

 

 

当用户名密码错误时,抛出异常

技术图片

 

Django rest framework 之认证

标签:mode   lib   用户信息   str   inf   view   object   密码   bsp   

原文地址:https://www.cnblogs.com/zhw3702/p/12362447.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!