You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask与Celery启动时模块导入冲突问题求助

Flask与Celery导入冲突问题及解决方案需求

在Flask应用中尝试同时启动Flask服务与Celery worker时,遇到模块导入冲突问题——两种启动方式对导入语法的要求相互矛盾,无法同时正常运行。

问题细节

1. 使用绝对导入时

在rentCanada.py中使用from config import Config:

  • Celery可正常启动,执行命令:
    celery -A rentCanada worker --loglevel=debug
    
  • 启动Flask时(执行flask run)报错:
    File "/home/rlm/Code/canadaAps/rentCanada.py", line 5, in <module>
        from config import Config
    ModuleNotFoundError: No module named 'config'
    

2. 改为相对导入后

将rentCanada.py中的导入改为from .config import Config:

  • Flask不再报config模块找不到的错误,但出现新错误:
    File "/home/rlm/Code/canadaAps/rentCanada.py", line 7, in <module>
        from scrapers.Scraper import Scraper
    ModuleNotFoundError: No module named 'scrapers'
    
  • 继续修改内部模块的导入(例如将/scrapers/Scraper.py中的from util.proxyTools import ProxyTools改为from ..util.proxyTools import ProxyTools),Flask可正常运行,但此时启动Celery会报错:
    File "/home/rlm/Code/canadaAps/rentCanada.py", line 5, in <module>
        from .config import Config
    ImportError: attempted relative import with no known parent package
    

项目目录结构

/rootDir
  __init__.py
  rentCanada.py <= flask入口文件
  config.py <= 待导入文件
  /scrapers
     __init__.py
     Scraper.py
  /blueprints
     __init__.py  # 及其他文件
  /api
     __init__.py # 及其他文件
  /util
     __init__.py # 及其他文件

Celery初始化代码(rentCanada.py中)

celery = Celery("rentCanada", broker=Config.CELERY_BROKER_URL, result_backend=Config.RESULT_BACKEND)

application = create_app(celery)

对Python 3.11的导入机制(尤其是__init__.py的作用)理解不足,现寻求可同时运行flask run与Celery启动命令的解决方案。

内容的提问来源于stack exchange,提问作者plutownium

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 17:30:51