Skip to content

Commit

Permalink
Merge pull request #1 from wuyue92tree/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
wuyue92tree authored Sep 9, 2018
2 parents b4911da + b665cc7 commit 90ca66b
Show file tree
Hide file tree
Showing 7 changed files with 156 additions and 4 deletions.
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ django-debug-toolbar==1.9.1
django-rest-swagger==2.2.0
djangorestframework==3.8.2
djangorestframework-jwt==1.11.0
django-filter==1.1.0
django-filter==2.0.0
Pillow==5.1.0
uwsgi==2.0.15
# https://github.com/darklow/django-suit/tarball/v2
24 changes: 24 additions & 0 deletions rest_backend/libs/accounts/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: wuyue
@contact: [email protected]
@software: IntelliJ IDEA
@file: urls.py
@create at: 2018-09-09 21:55
这一行开始写关于本文件的说明与解释
"""

from django.urls import path, include
from .views import *
from rest_framework import routers
#
# router = routers.DefaultRouter()
# router.register('profile', ProfileApiView.as_view())

urlpatterns = [
path('profile/', ProfileApiView.as_view()),
path('initToken/', InitToken.as_view()),
path('getToken/', GetToken.as_view())
]
96 changes: 96 additions & 0 deletions rest_backend/libs/accounts/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,101 @@
from __future__ import unicode_literals

from django.shortcuts import render
from rest_framework import generics
from rest_framework import serializers
from rest_framework.permissions import DjangoModelPermissions
from rest_framework.response import Response
from rest_framework import status
from .models import User
from rest_framework.authtoken.models import Token


# Create your views here.


class ProfileSerializer(serializers.ModelSerializer):
"""
序列化用户信息
"""

class Meta:
model = User
# fields = '__all__'
fields = (
'username', 'email', 'phone', 'nickname', 'is_superuser',
'is_staff',
'last_login', 'date_joined')
read_only_fields = (
'username', 'is_superuser', 'is_staff', 'last_login',
'date_joined')

# def update(self, instance, validated_data):


class ProfileApiView(generics.GenericAPIView):
"""
用户信息接口
parameters:
- name: data
type: json
required: true
location: form
"""
serializer_class = ProfileSerializer
filter_backends = None
pagination_class = None

def get(self, request):
queryset = User.objects.get(id=request.user.id)
serializer = self.get_serializer(queryset)
return Response(serializer.data)

def post(self, request):
instance = User.objects.get(id=request.user.id)
serializer = ProfileSerializer(data=request.data)
if serializer.is_valid():
serializer.update(instance=instance,
validated_data=serializer.validated_data)
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class GetToken(generics.GenericAPIView):
"""
获取Token令牌
"""
queryset = Token.objects.all()
permission_classes = [DjangoModelPermissions]
pagination_class = None

def get(self, request):
try:
access_token = self.get_queryset().get(user_id=request.user.id).key
return Response({'token': access_token})
except Token.DoesNotExist:
return Response({})
except Exception as e:
return Response({'系统异常: {}'.format(str(e))},
status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class InitToken(generics.GenericAPIView):
"""
初始化Token令牌
"""
queryset = Token.objects.all()
pagination_class = None
permission_classes = [DjangoModelPermissions]

def get(self, request):
try:
if len(Token.objects.filter(user_id=request.user.id)) > 0:
item = Token.objects.get(user_id=request.user.id)
item.delete()
new_item = Token.objects.create(user_id=request.user.id)
new_item.save()
return Response({'token': new_item.key})
except Exception as e:
return Response({'系统异常: {}'.format(str(e))},
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
2 changes: 1 addition & 1 deletion rest_backend/libs/backend/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@
path('docs/', schema_view),

# add api here

path('account/', include('rest_backend.libs.accounts.urls')),
]
15 changes: 13 additions & 2 deletions rest_backend/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
'corsheaders',
# rest接口框架
'rest_framework',
'rest_framework.authtoken',
# rest文档swagger
'rest_framework_swagger',
'rest_backend.libs.backend',
Expand All @@ -51,11 +52,16 @@
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',

'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# token参数认证
'rest_backend.utils.middleware.TokenAuthMiddleware',
# 跨域
'corsheaders.middleware.CorsMiddleware',
# 激活locale
'django.middleware.locale.LocaleMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
Expand All @@ -67,7 +73,7 @@
AUTH_USER_MODEL = 'accounts.User'

# session过期时间设置
SESSION_COOKIE_AGE = 60 * 30
SESSION_COOKIE_AGE = 3600 * 24

TEMPLATES = [
{
Expand Down Expand Up @@ -146,13 +152,18 @@
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'DEFAULT_FILTER_BACKENDS': [
'django_filters.rest_framework.DjangoFilterBackend',
],
'DEFAULT_PAGINATION_CLASS':
'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 10
}

Expand Down
20 changes: 20 additions & 0 deletions rest_backend/utils/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: wuyue
@contact: [email protected]
@software: PyCharm
@file: middleware.py
@create at: 2018-07-28 23:05
这一行开始写关于本文件的说明与解释
"""

from django.utils.deprecation import MiddlewareMixin


class TokenAuthMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.GET.get('token'):
request.META['HTTP_AUTHORIZATION'] = 'Token %s' % request.GET.get(
'token')
1 change: 1 addition & 0 deletions rest_backend/utils/suit.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class SuitConfig(DjangoSuitConfig):
ParentItem('认证和授权', children=[
ChildItem(model='accounts.user'),
ChildItem(model='auth.group'),
ChildItem(model='authtoken.token'),
], icon='fa fa-users'),
ParentItem('设置', children=[
# ChildItem('修改密码', url='admin:password_change'),
Expand Down

0 comments on commit 90ca66b

Please sign in to comment.