import os from pathlib import Path import dj_database_url from django.core.exceptions import ImproperlyConfigured BASE_DIR = Path(__file__).resolve().parent.parent PROJECT_ROOT = BASE_DIR.parent APP_VERSION = os.getenv("APP_VERSION", "1.2.1") SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", "dev-only-change-before-production") DEBUG = os.getenv("DJANGO_DEBUG", "true").lower() == "true" USE_HTTPS = os.getenv( "DJANGO_USE_HTTPS", "false" if DEBUG else "true", ).lower() == "true" if not DEBUG and SECRET_KEY == "dev-only-change-before-production": raise ImproperlyConfigured("生产环境必须设置 DJANGO_SECRET_KEY") ALLOWED_HOSTS = [ host.strip() for host in os.getenv("DJANGO_ALLOWED_HOSTS", "localhost,127.0.0.1,testserver").split(",") if host.strip() ] INSTALLED_APPS = [ "common.apps.HulumathAdminConfig", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "corsheaders", "rest_framework", "channels", "accounts", "math_life", "contest", "progression", "latex_lab", "content", "engagement", "toolbox", "common", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "corsheaders.middleware.CorsMiddleware", "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", "common.middleware.RequestIDMiddleware", ] ROOT_URLCONF = "config.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / "templates"], "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 = "config.wsgi.application" ASGI_APPLICATION = "config.asgi.application" DATABASE_URL = os.getenv("DATABASE_URL") if not DEBUG and not DATABASE_URL: raise ImproperlyConfigured("生产环境必须设置 MySQL DATABASE_URL") if not DEBUG and not DATABASE_URL.startswith("mysql://"): raise ImproperlyConfigured("生产环境 DATABASE_URL 必须使用 MySQL") DATABASES = { "default": dj_database_url.parse( DATABASE_URL or f"sqlite:///{BASE_DIR / 'db.sqlite3'}", conn_max_age=60, conn_health_checks=True, ) } if DATABASES["default"]["ENGINE"] == "django.db.backends.mysql": DATABASES["default"]["OPTIONS"] = { "charset": "utf8mb4", "init_command": ( "SET sql_mode='STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO," "NO_ENGINE_SUBSTITUTION'" ), "isolation_level": "read committed", } 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"}, ] AUTH_USER_MODEL = "accounts.User" LANGUAGE_CODE = "zh-hans" TIME_ZONE = "Asia/Shanghai" USE_I18N = True USE_TZ = True STATIC_URL = "/static/" STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_DIRS = [BASE_DIR / "static"] STORAGES = { "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"}, "staticfiles": { "BACKEND": ( "django.contrib.staticfiles.storage.StaticFilesStorage" if DEBUG else "whitenoise.storage.CompressedManifestStaticFilesStorage" ) }, } DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 20, "EXCEPTION_HANDLER": "common.api.exception_handler", "DEFAULT_THROTTLE_CLASSES": [ "rest_framework.throttling.AnonRateThrottle", "rest_framework.throttling.UserRateThrottle", ], "DEFAULT_THROTTLE_RATES": { "anon": os.getenv("API_ANON_RATE", "120/minute"), "user": os.getenv("API_USER_RATE", "600/minute"), "calculator": os.getenv("CALCULATOR_RATE", "30/minute"), }, } CORS_ALLOWED_ORIGINS = [ origin.strip() for origin in os.getenv("CORS_ALLOWED_ORIGINS", "http://localhost:3000").split(",") if origin.strip() ] CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = [ origin.strip() for origin in os.getenv("CSRF_TRUSTED_ORIGINS", "").split(",") if origin.strip() ] REDIS_URL = os.getenv("REDIS_URL") if not DEBUG and not REDIS_URL: raise ImproperlyConfigured("生产环境必须设置 Redis REDIS_URL") if REDIS_URL: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": {"hosts": [REDIS_URL]}, } } else: CHANNEL_LAYERS = { "default": {"BACKEND": "channels.layers.InMemoryChannelLayer"} } SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SAMESITE = "Lax" CSRF_COOKIE_SAMESITE = "Lax" SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") SECURE_CONTENT_TYPE_NOSNIFF = True X_FRAME_OPTIONS = "DENY" SECURE_SSL_REDIRECT = USE_HTTPS SESSION_COOKIE_SECURE = USE_HTTPS CSRF_COOKIE_SECURE = USE_HTTPS SECURE_HSTS_SECONDS = int( os.getenv("SECURE_HSTS_SECONDS", "31536000" if USE_HTTPS else "0") ) SECURE_HSTS_INCLUDE_SUBDOMAINS = USE_HTTPS SECURE_HSTS_PRELOAD = USE_HTTPS LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "standard": { "format": "%(asctime)s %(levelname)s %(name)s request_id=%(request_id)s %(message)s" } }, "filters": {"request_id": {"()": "common.logging.RequestIDFilter"}}, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "standard", "filters": ["request_id"], } }, "root": {"handlers": ["console"], "level": "INFO"}, }