Files
diary-family/diary_family/settings.py
xiaji 62c2f7d44f feat(settings): 添加CSRF受信任的源地址
允许来自指定IP地址的跨站请求,以支持特定环境下的访问需求
2026-01-29 21:58:32 +08:00

274 lines
8.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Django settings for diary_family project.
Generated by 'django-admin startproject' using Django 5.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/
"""
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/5.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-x^5b(t-qcpahyz+l^@3)lg_1d5@ks@jk*bqi042i7sle#vtmt('
# 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',
'core',
'django_celery_beat',
]
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 = 'diary_family.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 = 'diary_family.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/5.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/5.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Login URL configuration
LOGIN_URL = '/login/'
# Media files configuration
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
# Reports files configuration
REPORTS_URL = '/reports/'
REPORTS_ROOT = BASE_DIR / 'reports'
# Celery configuration
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERY_TIMEZONE = 'Asia/Shanghai'
CELERY_ENABLE_UTC = True
# Celery Beat configuration
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'
# Logging configuration
import os
from loguru import logger
LOG_DIR = BASE_DIR / 'logs'
LOG_DIR.mkdir(exist_ok=True)
# Configure loguru
logger.add(
LOG_DIR / 'app.log',
rotation='1 day',
retention='7 days',
compression='zip',
level='INFO'
)
# Internationalization
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
# Allow all hosts for development
ALLOWED_HOSTS = ['*']
# Template directories
TEMPLATES[0]['DIRS'] = [BASE_DIR / 'templates']
# Static files configuration
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = BASE_DIR / 'staticfiles'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_PORT = 25 # 或根据你的 SMTP 服务器设置
# Reports files configuration
REPORTS_URL = '/reports/'
REPORTS_ROOT = BASE_DIR / 'reports' # 可以修改为其他路径
# Django settings.py 中追加 Celery 日志配置
CELERY_LOG_FILE = "/var/log/celery/worker.log" # 你的指定日志路径
CELERY_LOG_LEVEL = "INFO" # 日志级别
CSRF_TRUSTED_ORIGINS = [
"http://14.103.237.41:16003",
# 如果你将来有域名,也可以在这里加上,例如 "https://yourdomain.com"
]
CELERY_BROKER_URL = 'redis://:xjjq1234!@localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://:xjjq1234!@localhost:6379/0'
LOGGING = {
'version': 1,
'disable_existing_loggers': False, # 不关闭已存在的日志器
'formatters': {
'standard': { # 统一的标准日志格式
'format': '[%(asctime)s] [%(levelname)s] [%(process)d] [%(module)s] %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S'
},
'syslog': { # syslog格式用于fail2ban检测
'format': '%(name)s: %(levelname)s %(message)s'
},
},
'handlers': {
'file': { # 日志写入文件的处理器
'level': 'INFO', # 日志级别INFO及以上都记录ERROR/WARNING/INFO
'class': 'logging.handlers.RotatingFileHandler', # 日志轮转,防止文件过大
# ✅ 核心pathlib对象转字符串logging只接收字符串路径必转
'filename': str(LOG_DIR / 'all_in_one.log'),
'maxBytes': 1024 * 1024 * 100, # 单个日志文件最大100MB
'backupCount': 10, # 最多保留10个日志备份
'formatter': 'standard', # 使用上面定义的统一格式
'encoding': 'utf-8', # 编码,防止中文乱码
},
'console': { # 兼容控制台输出(开发调试用,不影响生产)
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'standard'
},
'syslog': { # syslog处理器用于fail2ban检测登录失败
'level': 'WARNING',
'class': 'logging.handlers.SysLogHandler',
'address': '/dev/log', # Linux系统日志socket
'facility': 'local0',
'formatter': 'syslog',
},
'auth_file': { # 认证日志文件处理器(备选方案)
'level': 'WARNING',
'class': 'logging.handlers.RotatingFileHandler',
'filename': str(LOG_DIR / 'auth.log'),
'maxBytes': 1024 * 1024 * 50, # 50MB
'backupCount': 5,
'formatter': 'standard',
'encoding': 'utf-8',
},
},
# 所有日志器配置和原配置完全一致,无需任何修改
'loggers': {
'django': { # Django核心日志
'handlers': ['file'],
'level': 'INFO',
'propagate': True,
},
'django.request': { # Django的请求日志
'handlers': ['file'],
'level': 'INFO',
'propagate': True,
},
'django.security.login': { # 登录安全日志用于fail2ban
'handlers': ['syslog', 'auth_file'],
'level': 'WARNING',
'propagate': False,
},
'celery': { # Celery客户端日志Django中提交任务的日志
'handlers': ['file'],
'level': 'INFO',
'propagate': True,
},
'utils.tasks': { # Celery邮件任务模块
'handlers': ['file'],
'level': 'INFO',
'propagate': True,
},
'utils.email_utils': { # 邮件配置模块
'handlers': ['file'],
'level': 'INFO',
'propagate': True,
},
},
}