# 视图和调度模块:views.py from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from .backup_utils import backup_database from apscheduler.schedulers.background import BackgroundScheduler from django.conf import settings import logging logger = logging.getLogger(__name__) # 初始化调度器 scheduler = BackgroundScheduler() def scheduled_backup(): """定时备份任务""" try: backup_path = backup_database() logger.info(f"定时备份完成: {backup_path}") except Exception as e: logger.error(f"定时备份失败: {str(e)}") # 启动定时备份(每小时执行一次) if not scheduler.running: scheduler.add_job( scheduled_backup, 'cron', hour='*/6', # 每6小时执行一次 minute=0, # 在0分钟时执行 id='db_backup_job' ) scheduler.start() @csrf_exempt @require_POST def trigger_backup(request): """手动触发备份的API接口""" try: backup_path = backup_database() return JsonResponse({ 'status': 'success', 'message': 'Database backup completed', 'path': backup_path }) except Exception as e: return JsonResponse({ 'status': 'error', 'message': str(e) }, status=500)