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