DRF有丰富的功能,JWT认证、过滤、分页、异常处理、接口文档、限流、缓存等。
这些配置,有些需要写自定义接口,有些只需要配置就可以了。
1 在INSTALLED_APPS中,增加两个应用
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', # djangorestframework框架
'django_filters',
# 增加其它应用
]
2 编写自定义异常
在GeneralTools目录下创建Exceptions.py文件,内容如下:
from rest_framework.views import exception_handler as drf_exception_handler
import logging
from django.db import DatabaseError
from redis.exceptions import RedisError
from rest_framework.response import Response
from rest_framework import status
# 获取在配置文件中定义的logger,用来记录日志
logger = logging.getLogger('tongheng2')
def exception_handler(exc, context):
"""
自定义异常处理
:param exc: 异常
:param context: 抛出异常的上下文
:return: Response响应对象
"""
# 调用drf框架原生的异常处理方法
response = drf_exception_handler(exc, context)
if response is None:
view = context['view']
if isinstance(exc, DatabaseError) or isinstance(exc, RedisError):
# 数据库异常
logger.error('[%s] %s' % (view, exc))
response = Response({'message': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
return response
3 增加REST_FRAMEWORK配置
REST_FRAMEWORK = {
# JWT 认证
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # JWT认证
'rest_framework.authentication.SessionAuthentication', # session认证
'rest_framework.authentication.BasicAuthentication', # 基本认证
),
# 过滤Filtering
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
# 分页Pagination
# 也可通过自定义Pagination类,来为视图添加不同分页行为。在视图中通过pagination_clas属性来指明。
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10, # 每页数目
# 异常处理(自定义异常)
'EXCEPTION_HANDLER': 'GeneralTools.Exceptions.exception_handler',
# 接口文档
# 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema',
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
# 限流
'DEFAULT_THROTTLE_CLASSES': (
# 'rest_framework.throttling.AnonRateThrottle', # 限制所有匿名未认证用户
# 'rest_framework.throttling.UserRateThrottle', # 限制所有用户
'rest_framework.throttling.ScopedRateThrottle', # 限制用户对每个视图的访问频次
),
'DEFAULT_THROTTLE_RATES': {
# 'anon': '1/minute',
# 'user': '1/minute' # 限制用户对所有接口访问频次
'org_home': '1/minute' # 限制匿名用户或注册用户对接口的访问频次
}
}
4 指定JWT认证返回数据格式
在GeneralTools目录下创建JwtHandler.py文件,内容如下:
import logging
# 获取在配置文件中定义的logger,用来记录日志
# 注:其中的tongheng2必须和配置文件中指定的配置路径一致。
logger = logging.getLogger('tongheng2')
def jwt_response_payload_handler(token, user=None, request=None):
"""
【功能描述】直接使用DRF-JWT提供的视图方法时,其默认的返回值只有token,若需要前端接收到用户其它信息,
需要重写jwt_response_payload_handler方法。
"""
return {
'id': user.id,
'username': user.username,
'photo_url': user.photo_url,
'mobile': user.mobile,
'openid': user.openid,
'token': token
}
5 增加JWT_AUTH配置
JWT_AUTH = {
# 设置生成(签发)jwt token时token有效时间
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
# 指定JWT 扩展登录视图生成响应数据调用函数
'JWT_RESPONSE_PAYLOAD_HANDLER':
'GeneralTools.JwtHandler.jwt_response_payload_handler'
}
6 增加DRF扩展配置
REST_FRAMEWORK_EXTENSIONS = {
# 缓存时间,单位秒(24小时)
'DEFAULT_CACHE_RESPONSE_TIMEOUT': 24 * 60 * 60,
# 缓存存储
'DEFAULT_USE_CACHE': 'default',
}
浙公网安备 33010602011771号