项目公共部分
响应文件
###response.py
from rest_framework.response import Response
class APIResponse(Response):
def __init__(self, data_status=0, data_msg='ok', results=None, http_status=None, headers=None, exception=False, **kwargs):
data = {
'status': data_status,
'msg': data_msg,
}
if results is not None:
data['results'] = results
data.update(kwargs)
super().__init__(data=data, status=http_status, headers=headers, exception=exception)
异常模块
###exception.py
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.views import Response
from rest_framework import status
from utils.logging import logger
def exception_handler(exc, context):
response = drf_exception_handler(exc, context)
# 异常模块就是记录项目的错误日志
logger.error('%s - %s - %s' % (context['view'], context['request'].method, exc))
if response is None:
return Response({
'detail': '%s' % exc
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)
return response
日志模块
##logging.py
import logging
logger = logging.getLogger('django')
配置文件
##注册app
INSTALLED_APPS=[
'app.app名', ##注册多个app
'rest_framwork', ##使用drf
'xadmin', ##注册xadmin后台
]
MIDDLEWARE=[
'corsheaders.middleware.CorsMiddleware', ##定义自定义中间件
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'ims', ##数据库名
'USER':'root', ##用户名
'PASSWORD':'123456' ##密码
}
}
import pymysql
pymysql.install_as_MySQLdb()
STATIC_URL = '/static/'
# 媒体文件配置
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
REST_FRAMEWORK = {
# 'DEFAULT_AUTHENTICATION_CLASSES':'JSONWebTokenAuthentication',
'EXCEPTION_HANDLER': 'utils.exception.exception_handler',
'DEFAULT_THROTTLE_RATES': {
'sms': '1/min',
},
}
##jwt认证
import datetime
JWT_AUTH = {
# token过期时间
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
# 是否允许刷新及刷新的过期时间
'JWT_ALLOW_REFRESH': False,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
# token校验前缀
'JWT_AUTH_HEADER_PREFIX': 'JWT',
# token md5 加密盐
'JWT_SECRET_KEY': SECRET_KEY,
}
既然选择了远方,只能风雨兼程