media
目录media
)LuffyAPI/LuffyAPI
下新建media
文件夹该文件夹用于存放媒体文件
settings/dev.py
中添加# media的配置
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
pillow
模块pip install pillow
LuffyAPI/LuffyAPI/apps/user/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
mobile = models.CharField(max_length=11, unique=True)
# 需要pillow包的支持
icon = models.ImageField(upload_to='icon', default='icon/default.png')
class Meta:
db_table = 'luffy_user' # 指定表名为
verbose_name = '用户表'
verbose_name_plural = verbose_name
def __str__(self):
return self.username
media
文件夹下创建icon
文件夹,并放入1个default.png
文件,作为用户默认头像settings/dev.py
中添加如下代码# 自定义User表
AUTH_USER_MODEL = 'user.User'
user
的配置,否则需要删库删表,删admin
,auth
的迁移文件① 切换到项目根路径(有manage.py
的那个路径)
② 执行数据迁移文件
python manage.py makemigrations
python manage.py migrate
LuffyAPI/LuffyAPI/urls.py
from django.contrib import admin
from django.urls import path, re_path, include
from django.conf import settings
from django.views.static import serve
urlpatterns = [
path('admin/', admin.site.urls),
# media路径开放
re_path('^media/(?P.*)' , serve, {'document_root': settings.MEDIA_ROOT}),
path('user/', include('user.urls')),
path('home/', include('home.urls')),
path('order/', include('order.urls')),
path('course/', include('course.urls')),
]
LuffyAPI/LuffyAPI/apps
下的user
、home
、order
、course
创建urls.py
,内容如下from django.contrib import admin
from django.urls import path, re_path, include
from django.conf import settings
from django.views.static import serve
urlpatterns = [
]
utils
下创建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 get_logger
logger = get_logger('django')
def exception_handler(exc, context):
response = drf_exception_handler(exc, context)
if response is None: # 有异常
# 记录服务器异常
logger.critical('%s' % exc)
response = Response({'detail': '服务器异常,请重试...'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return response
settings/dev.py
中添加REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'utils.exception.exception_handler',
}
Response
utils
下创建response.py
from rest_framework.response import Response
class APIResponse(Response):
def __init__(self, status=0, msg='ok', http_status=None, headers=None, exception=False, **kwargs):
data = {
'status': status,
'msg': msg,
}
if kwargs:
data.update(kwargs)
super().__init__(data=data, status=http_status, headers=headers, exception=exception)
utils
下创建logging.py
import logging
logger = logging.getLogger('django')
settings/dev.py
中添加LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
},
},
'filters': {
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'handlers': {
'console': {
# 实际开发建议使用WARNING
'level': 'DEBUG',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'file': {
# 实际开发建议使用ERROR
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
# 日志位置,日志文件名,日志保存目录必须手动创建,注:这里的文件路径要注意BASE_DIR代表的是小luffyapi
'filename': os.path.join(os.path.dirname(BASE_DIR), "logs", "luffy.log"),
# 日志文件的最大值,这里我们设置300M
'maxBytes': 300 * 1024 * 1024,
# 日志文件的数量,设置最大日志数量为10
'backupCount': 10,
# 日志格式:详细格式
'formatter': 'verbose',
# 文件内容编码
'encoding': 'utf-8'
},
},
# 日志对象
'loggers': {
'django': {
'handlers': ['console', 'file'],
'propagate': True, # 是否让日志信息继续冒泡给其他的日志处理系统
},
}
}