Django setting配置
1、setting.py文件
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'huk3b9i-0pot^^!=3(ko=+#g8vt67l7%(gl_p*$(e+%kpys6x!' # 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', 'project_core', ] 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 = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ # 自己 'web/dist', ], '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', # u"在模板变量中添加 {{ MEDIA_URL }}" "django.template.context_processors.media", # u"在模板变量中添加 {{ STATIC_URL }}" "django.template.context_processors.static", ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mysite', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': 3306, 'ATOMIC_REQUESTS': True, } } # Password validation # https://docs.djangoproject.com/en/3.1/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/3.1/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/3.1/howto/static-files/ STATIC_URL = '/static/' # collectstatic 命令收集静态文件的目录 STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "web/dist/static"), ] # media目录 上传文件存储目录 MEDIA_ROOT = os.path.join(BASE_DIR, 'media') if not os.path.exists(os.path.join(BASE_DIR, 'media')): os.makedirs(os.path.join(BASE_DIR, 'media')) # 例子: "/static/" or "http://media.example.com/" MEDIA_URL = '/media/' # ======session配置====== # session使用redis SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' # 使用cache对应的别名 SESSION_CACHE_ALIAS = "default" # 子域名共享session的设置 # SESSION_COOKIE_DOMAIN = '.example.com' # session序列化 SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' # ======缓存配置====== CACHES = { # 生产环境使用 "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/3", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", 'CULL_FREQUENCY': 3, # 用于 compression "COMPRESS_MIN_LEN": 10, }, 'TIMEOUT': 18000, # 5hours 默认是300秒 }, # 文件系统缓存 'file_cache': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': os.path.join(BASE_DIR, 'files_cache'), 'TIMEOUT': 18000, # 5 hours 'OPTIONS': { 'MAX_ENTRIES': 10000, 'CULL_FREQUENCY': 3, } }, # 本地内存 'local_cache': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', 'options': { 'MAX_ENTRIES': 1024, } }, } # ======日志配置====== # NOTSET < DEBUG < INFO < WARNING < ERROR < CRITICAL if not os.path.exists(os.path.join(BASE_DIR, 'logs')): os.makedirs(os.path.join(BASE_DIR, 'logs')) LOGS_ROOT = os.path.join(BASE_DIR, 'logs') LOGGING = { 'version': 1, 'disable_existing_loggers': True, # 日志格式 'formatters': { 'standard': { 'format': '[%(levelname)s] %(asctime)s [%(threadName)s:%(thread)s prototype] [%(name)s:%(lineno)s prototype] [%(module)s:%(funcName)s] - %(message)s' }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, # 用来定义具体处理日志的方式 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'default': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(LOGS_ROOT, 'all.log'), # 日志输出文件 'maxBytes': 1024 * 1024 * 5, # 5 MB # 文件大小 'backupCount': 60, # 备份份数 'formatter': 'standard', # 使用哪种日志格式 }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', # 输出到控制台 'formatter': 'standard' }, 'request_handler': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', # 输出到文件 'filename': os.path.join(LOGS_ROOT, 'django_request.log'), 'maxBytes': 1024 * 1024 * 5, # 5 MB 'backupCount': 60, 'formatter': 'standard', }, 'exception_handler': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(LOGS_ROOT, 'exception.log'), 'maxBytes': 1024 * 1024 * 5, # 5 MB 'backupCount': 60, 'formatter': 'standard', }, }, # 配置用那种handlers来处理日志 'loggers': { 'django': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False }, # 某个app专用 'BangSo.app': { 'handlers': ['default', 'console'], 'level': 'DEBUG', 'propagate': True }, 'django.request': { 'handlers': ['request_handler'], 'level': 'INFO', 'propagate': False }, 'exception': { 'handlers': ['exception_handler'], 'level': 'ERROR', 'propagate': False }, } } # ======rest api配置====== REST_FRAMEWORK = { # 自定义异常处理方法 'EXCEPTION_HANDLER': 'project_core.exception.api_exception', # 全局权限控制 'DEFAULT_PERMISSION_CLASSES': [ 'project_core.permission.AppApiPermission' ], # 默认解释器类 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', 'rest_framework.parsers.JSONParser', ), # 默认渲染器类 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer' ), # 授权处理 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', # 重写上面的rest_framework中TokenAuthentication中的 authenticate_credentials(token验证) 方法 'api_core.authentication.ExpiringTokenAuthentication', ), 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema' # # 全局级别的过滤组件,查找组件,排序组件 # 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.SearchFilter', 'rest_framework.filters.DjangoFilterBackend', # 'rest_framework.filters.OrderingFilter',), # 分页组件 # 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', # 'PAGE_SIZE': 5 } # 定时任务 django-celery # Celery使用redis作为broker. BROKER_URL = 'redis://127.0.0.1:6379/5' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/6' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' # 定期任务 # 任务结果过期 CELERY_TASK_RESULT_EXPIRES = 7*86400 # 7 days # 是否需要监控 CELERY_SEND_EVENTS = True CELERY_TIMEZONE = 'Asia/Shanghai' # 每个子项的最大任务数 CELERYD_MAX_TASKS_PER_CHILD = 3 # ======django-cors-headers配置 处理跨域请求问题====== CORS_ORIGIN_ALLOW_ALL = True
2、自定义异常处理方法project_core.exception.api_exception所在的文件:exception.py
from django.http import Http404 from django.core.exceptions import PermissionDenied from rest_framework.response import Response from rest_framework.exceptions import APIException, AuthenticationFailed from rest_framework import status from rest_framework.views import set_rollback from django.utils.translation import ugettext_lazy def api_exception(exc, context): """ api异常处理方法 默认情况下,使用的是 REST framework `APIException` 和 Django 内置的 `Http404`、 `PermissionDenied` exceptions 返回None将引发500错误。 """ if isinstance(exc, APIException): headers = {} if getattr(exc, 'auth_header', None): headers['WWW-Authenticate'] = exc.auth_header if getattr(exc, 'wait', None): headers['Retry-After'] = '%d' % exc.wait if isinstance(exc.detail, (list, dict)): # data = exc.detail data = {'code': 0, 'message': exc.detail} else: data = {'code': 0, 'message': exc.detail} # 授权失败 if isinstance(exc, AuthenticationFailed): data['code'] = -1 set_rollback() return Response(data, status=exc.status_code, headers=headers) # 没找到 elif isinstance(exc, Http404): data = {'code': 0, 'message': ugettext_lazy('没找到')} set_rollback() return Response(data, status=status.HTTP_404_NOT_FOUND) # 权限被拒绝 elif isinstance(exc, PermissionDenied): data = {'code': 0, 'message': ugettext_lazy('权限被拒绝')} set_rollback() return Response(data, status=status.HTTP_403_FORBIDDEN) # Note: 未处理的异常将引发500错误。 return None
3、全局权限控制类project_core.permission.AppApiPermission所在的permission.py文件
from rest_framework import permissions from django.contrib.auth.models import User class AppApiPermission(permissions.BasePermission): """ 全局权限控制类 """ # 不需要检查的url un_auth_url = [] def has_permission(self, request, view): """ 返回false会被拦截 """ if request.path in self.un_auth_url: return True # 判断是否非法用户 if request.user and isinstance(request.user, User): return True # if ..... return False
4、token授权校验project_core.authentication.ExpiringTokenAuthentication中的authentication.py文件
import datetime from rest_framework.authentication import TokenAuthentication from project_core.models import AppToken from rest_framework import exceptions from django.conf import settings class ExpiringTokenAuthentication(TokenAuthentication): model = AppToken def authenticate_credentials(self, key): try: token = self.model.objects.get(key=key) except self.model.DoesNotExist: raise exceptions.AuthenticationFailed(u'无效的Token') if not token.user.available: raise exceptions.AuthenticationFailed(u'用户已失效或删除') local_now = datetime.datetime.now() # token有效时间 if token.created < local_now - datetime.timedelta(hours=settings.TOKEN_EXPIRE_TIME): raise exceptions.AuthenticationFailed(u'Token已过期') # 刷新token if token: token.created = local_now token.save(update_fields=('created',)) return (token.user, token)
5、token模型类所在的model.py文件
import os import binascii from django.db import models from django.conf import settings class AppToken(models.Model): """ 存放token的自定义model """ key = models.CharField(max_length=40, primary_key=True) user = models.OneToOneField('用户表', related_name='auth_app_token', on_delete=models.DO_NOTHING) created = models.DateTimeField(auto_now_add=True) class Meta: abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS def save(self, *args, **kwargs): if not self.key: self.key = binascii.hexlify(os.urandom(20)).decode() return super(AppToken, self).save(*args, **kwargs) def __str__(self): return self.key
微信搜索公众号“算联多优惠神器”,每天都可以领取美团、饿了么的红包优惠券,还有京东、淘宝、拼多多的购物优惠券,更有景区特价门票、动车飞机特价票!!!