我想先通过 RabbitMQ 运行一个简单的测试(运行任务(,一旦正确设置,然后封装在 Docker 中并从那里运行。
我的结构如下所示:
-rabbitmq_docker
- test_celery
- __init__.py
- celeryapp.py
- celeryconfig.py
- runtasks.py
- tasks.py
- docker-compose.yml
- dockerfile
- requirements.txt
celeryconfig.py
## List of modules to import when celery starts
CELERY_IMPORTS = ['test_celery.tasks',] # Required to import module containing tasks
## Message Broker (RabbitMQ) settings
CELERY_BROKER_URL = "amqp://guest@localhost//"
CELERY_BROKER_PORT = 5672
CELERY_RESULT_BACKEND = 'rpc://'
celeryapp.py
from celery import Celery
app = Celery('test_celery')
app.config_from_object('test_celery.celeryconfig', namespace='CELERY')
__init__.py
from .celeryapp import app as celery_app
run_tasks.py
from tasks import reverse
from celery.utils.log import get_task_logger
LOGGER = get_task_logger(__name__)
if __name__ == '__main__':
async_result = reverse.delay("rabbitmq")
LOGGER.info(async_result.get())
tasks.py
from test_celery.celeryapp import app
@app.task(name='tasks.reverse')
def reverse(string):
return string[::-1]
我从rabbitmq_docker
目录中运行celery -A test_celery worker --loglevel=info
。然后在导入所需模块后,在单独的窗口中,我在 Python 控制台中触发reverse.delay("rabbitmq")
。这行得通。现在,当我尝试通过run_tasks.py
触发反向功能时,即 python test_celery/run_tasks.py
我得到:
Traceback (most recent call last):
File "test_celery/run_tasks.py", line 1, in <module>
from tasks import reverse
File "/Users/my_mbp/Software/rabbitmq_docker/test_celery/tasks.py", line 1, in <module>
from test_celery.celeryapp import app
ModuleNotFoundError: No module named 'test_celery'
我不明白的是为什么直接从 Python 控制台调用时不会抛出此回溯。谁能在这里帮我?我最终想启动 docker,然后自动运行测试(无需进入 Python 控制台(。
问题仅仅是因为你的模块不在 Python 路径中。这些应该会有所帮助:
- 指定 PYTHONPATH 以指向test_celery打包的目录。
- 始终在test_celery包所在的目录中运行 Python 代码。
- 或者重新组织您的进口...