修复Django应用启动时的导入错误

- 在knowledge/apps.py的ready()方法中注册Celery任务
- 移除ops/__init__.py中的直接导入,避免循环依赖
- 简化tasks/__init__.py,使用延迟导入
- 解决"Apps aren't loaded yet"错误

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
朱潮 2025-08-31 01:25:16 +08:00
parent 10e38b2c05
commit dea3454011
3 changed files with 37 additions and 26 deletions

View File

@ -4,3 +4,36 @@ from django.apps import AppConfig
class KnowledgeConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'knowledge'
def ready(self):
"""在Django应用准备好后注册Celery任务"""
try:
# 导入Celery应用
from ops import celery_app
# 注册高级学习任务
try:
from knowledge.tasks.advanced_learning import (
advanced_learning_by_document,
batch_advanced_learning
)
celery_app.register_task(advanced_learning_by_document)
celery_app.register_task(batch_advanced_learning)
print("✅ Advanced learning tasks registered via app config")
except ImportError as e:
print(f"❌ Failed to register advanced learning tasks: {e}")
# 注册媒体学习任务
try:
from knowledge.tasks.media_learning import (
media_learning_by_document,
media_learning_batch
)
celery_app.register_task(media_learning_by_document)
celery_app.register_task(media_learning_batch)
print("✅ Media learning tasks registered via app config")
except ImportError as e:
print(f"❌ Failed to register media learning tasks: {e}")
except Exception as e:
print(f"⚠️ Failed to register tasks via app config: {e}")

View File

@ -1,6 +1,5 @@
# coding=utf-8
# Import tasks for Celery discovery
# Note: We import the specific tasks, not * to avoid circular imports
from .advanced_learning import advanced_learning_by_document, batch_advanced_learning
from .media_learning import media_learning_by_document, media_learning_batch
# Note: We use lazy imports to avoid Django app loading issues
# Tasks will be imported when needed by Celery's autodiscover

View File

@ -8,26 +8,5 @@
"""
from .celery import app as celery_app
# Import and register advanced learning tasks
try:
from knowledge.tasks.advanced_learning import (
advanced_learning_by_document,
batch_advanced_learning
)
# Register tasks with the celery app
celery_app.register_task(advanced_learning_by_document)
celery_app.register_task(batch_advanced_learning)
except ImportError:
pass
# Import and register media learning tasks
try:
from knowledge.tasks.media_learning import (
media_learning_by_document,
media_learning_batch
)
# Register tasks with the celery app
celery_app.register_task(media_learning_by_document)
celery_app.register_task(media_learning_batch)
except ImportError:
pass
# 任务注册现在通过knowledge/apps.py的ready()方法处理
# 这样可以避免Django应用未准备好时的导入问题