Files
template/config/base.py
2025-12-21 00:20:27 +08:00

83 lines
2.7 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.
"""
基础配置类
包含所有环境通用的配置项
"""
import os
from datetime import timedelta
class Config:
"""
基础配置类
所有环境配置都继承此类
"""
# Flask基础配置
SECRET_KEY = os.environ.get('SECRET_KEY')
if not SECRET_KEY:
raise ValueError("SECRET_KEY 环境变量未设置,请在.env文件中配置")
# 数据库配置
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///app.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ENGINE_OPTIONS = {
'pool_pre_ping': True, # 连接前检查连接是否有效
'pool_recycle': 300, # 连接回收时间(秒)
}
# 跨域配置
CORS_ORIGINS = os.environ.get('CORS_ORIGINS', '*').split(',')
# 日志配置
LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO')
LOG_FILE = os.environ.get('LOG_FILE', 'logs/app.log')
# 缓存配置
CACHE_TYPE = os.environ.get('CACHE_TYPE', 'simple')
CACHE_DEFAULT_TIMEOUT = int(os.environ.get('CACHE_DEFAULT_TIMEOUT', 300))
# Redis缓存配置当CACHE_TYPE=redis时使用
REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379/0')
# 会话配置
PERMANENT_SESSION_LIFETIME = timedelta(
hours=int(os.environ.get('SESSION_LIFETIME_HOURS', 24))
)
# 文件上传配置
MAX_CONTENT_LENGTH = int(os.environ.get('MAX_CONTENT_LENGTH', 16 * 1024 * 1024)) # 16MB
UPLOAD_FOLDER = os.environ.get('UPLOAD_FOLDER', 'uploads')
# 安全配置
WTF_CSRF_ENABLED = os.environ.get('WTF_CSRF_ENABLED', 'True').lower() == 'true'
WTF_CSRF_TIME_LIMIT = int(os.environ.get('WTF_CSRF_TIME_LIMIT', 3600))
@staticmethod
def init_app(app):
"""
初始化应用配置
创建必要的目录和配置日志
"""
# 创建必要的目录
os.makedirs('logs', exist_ok=True)
os.makedirs('uploads', exist_ok=True)
# 配置日志
import logging
from logging.handlers import RotatingFileHandler
if not app.debug and not app.testing:
file_handler = RotatingFileHandler(
Config.LOG_FILE,
maxBytes=10240000, # 10MB
backupCount=10
)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
))
file_handler.setLevel(getattr(logging, Config.LOG_LEVEL))
app.logger.addHandler(file_handler)
app.logger.setLevel(getattr(logging, Config.LOG_LEVEL))
app.logger.info('应用启动')