# -*- 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配置全局認證django
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ['app.utils.auth.FirstAuthtication', 'app.utils.auth.Authtication'] }
django-rest-swagger配置json
# 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.pyapi
# -*- 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')