标签:mode lib 用户信息 str inf view object 密码 bsp
先将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 ]
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()),
]
创建两张表,一个存用户信息,一个存用户登录后的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)
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
如果用户名和密码正确,会生成token,下次登录时,token的值会更新
当用户名密码错误时,抛出异常
标签:mode lib 用户信息 str inf view object 密码 bsp
原文地址:https://www.cnblogs.com/zhw3702/p/12362447.html