一、环境搭建
pip install django
二、创建项目
django-admin startproject 项目名
# 例:
django-admin startproject taobao_mall
三、创建应用
cd 项目根目录
# manage.py 为上述创建项目时自动生成的管理文件
python manage.py startapp 应用名
# 例:
python manage.py startapp users
四、用户模型类
使用Django提供的认证系统:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
"""
用户信息
"""
mobile = models.CharField(max_length=11, unique=True, verbose_name="手机号")
class Meta:
db_table = "tb_users"
verbose_name = "用户信息"
verbose_name_plural = verbose_name
在配置文件中进行设置
# 设置使用django中的用户认证模型类
# 必须在第一次数据迁移之前声明
AUTH_USER_MODEL = 'users.User' # 这里官方要求只能有一个<子应用目录.模型类名>
报错:AttributeError: type object ‘User’ has no attribute ‘USERNAME_FIELD’,查看是否继承的AbstractUser类,误写成了AbstractbaseUser。
五、数据库配置与迁移
Django项目默认 sqlite3 数据库, 生成的数据库名为 db.sqlite3(应用场景:测试),因此,我们需要将其配置为mysql:
1、创建数据库
create database taobao default charset=utf8; # 不指定charset,默认使用的是Latin
创建数据库用户
# 创建用户
create user taobao_user identified by 'taobao';
# 授权
grant all on taobao.* to 'taobao_user'@'%';
# 刷新权限
flush privileges;
2、配置数据库连接
在配置文件下,修改DATABASES字段:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"HOST": "127.0.0.1",
"PORT": 3306,
"USER": "taobao_user",
"PASSWORD": "taobao",
"NAME": "taobao_mall",
}
}
3、数据库迁移
在项目目录下,执行:
# 生成迁移文件
python manage.py makemigrations
# 生成数据库表
python manage.py migrate
六、异常处理
新建utils/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 = logging.getLogger('django')
def exception_handler(exc, context):
"""
自定义异常处理
:param exc: 异常
:param context: 抛出异常的上下文
:return: Response响应对象
"""
# 调用drf框架原生的异常处理方法
response = drf_exception_handler(exc, context)
# 系统内部没有报错或者错误不被drf所识别,则返回None
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
在配置文件中添加:
# 修改rest_framework中的异常处理机制
REST_FRAMEWORK = {
# 异常处理
'EXCEPTION_HANDLER': 'meiduo_mall.utils.exceptions.exception_handler',
}
七、配置文件说明
"""
Django settings for MeiDou_Mall project.
Generated by 'django-admin startproject' using Django 2.2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
import sys
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 将apps的路径添加都系统的路径中,以简写文件的路径信息
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '@#u(4z-b$@evxjxvq7hw+&gvy_b72go-(pb&xy^92x7ug(jksm'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# 允许访问的主机
ALLOWED_HOSTS = ["*"]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 注册用户模块
'users.apps.UsersConfig'
]
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',
]
ROOT_URLCONF = 'MeiDou_Mall.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 指定模板路径
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'MeiDou_Mall.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'mysql': {
"ENGINE": "django.db.backends.mysql",
"HOST": "127.0.0.1",
"PORT": 3306,
"USER": "meiduo_user",
"PASSWORD": "meiduo",
"NAME": "meiduo_mall",
}
}
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/0",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
"session": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.01:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "session"
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
# 语言
LANGUAGE_CODE = 'zh-hans'
# 时区
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
# 访问静态文件用到的url前缀
STATIC_URL = '/static/'
# 告知Django静态文件保存在哪个目录下
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_files')]
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': {
'level': 'DEBUG',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
# 把日志记录到文件
'file': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
# 日志路径
'filename': os.path.join(os.path.dirname(BASE_DIR), "logs/meiduo.log"),
'maxBytes': 300 * 1024 * 1024,
'backupCount': 10,
'formatter': 'verbose'
},
},
# 日志器:程序记录日志时的操作对象
'loggers': { # 定义一个名为django的日志器
'django': {
'handlers': ['console', 'file'],
# 设置是否运行日志向上一级日志功能传递
'propagate': True,
},
}
}
# 修改rest_framework中的异常处理机制
REST_FRAMEWORK = {
# 异常处理
'EXCEPTION_HANDLER': 'meiduo_mall.utils.exceptions.exception_handler',
}
# 设置使用django中的用户认证模型类
# 必须在第一次数据迁移之前声明
AUTH_USER_MODEL = 'users.User' # 这里官方要求只能有一个<子应用目录.模型类名>