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

Flask项目运行pytest时持续出现ModuleNotFoundError(找不到'app'模块)的问题求助

Flask项目运行pytest时持续出现ModuleNotFoundError(找不到'app'模块)的问题求助

大家好,我最近碰到一个卡了好久的问题,想请各位帮忙排查下。

我的Flask后端目录结构是这样的:

backend/
   ├── app/
   │   ├── __init__.py
   │   ├── routes/
   │   │   ├── dev_routes.py
   │   │   └── ...
   │   └── models.py
   ├── tests/
   │   ├── __init__.py
   │   └── routes/
   │       └── test_dev_routes.py
   └── main.py
   |__ ...

我现在在终端的backend目录下,用命令pytest tests/routes尝试运行test_dev_routes.py,但一直弹出下面的错误:

_______ ERROR collecting tests/routes/test_dev_routes.py ________
ImportError while importing test module '/Users/name/folder/project-name/project/backend/tests/routes/test_dev_routes.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
../../../../miniconda3/lib/python3.10/importlib/__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/routes/test_dev_routes.py:3: in <module>
    from app.routes import dev_routes
E   ModuleNotFoundError: No module named 'app'

我的test_dev_routes.py代码如下:

import pytest
from flask import Flask, json
from app.routes import dev_routes
from app import create_app, db
from app.models import User, Doctor, Slot, Queue, QueueEntry

@pytest.fixture
def client():
    app = Flask(__name__)
    app.register_blueprint(dev_routes.api, url_prefix='/api/dev')
    app.config['TESTING'] = True
    with app.test_client() as client:
        with app.app_context():
            db.create_all()  # Create the database tables
        yield client
        with app.app_context():
            db.drop_all()  # Clean up after tests

dev_routes.py里定义了api = Blueprint('dev_api', __name__),在app目录内的其他文件里引用这个变量是完全正常的。我试过把tests/routes文件夹移到app目录里,结果还是遇到同样的错误,实在搞不清哪里出问题了。

另外,我的app/__init__.py内容是这样的:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS

db = SQLAlchemy()
_app_instance = None  # Singleton instance

def create_app(config_name: str = None):
    global _app_instance
    if _app_instance is None:
        _app_instance = Flask(__name__)
        _app_instance.config.from_object('config.Test')
        db.init_app(_app_instance)
        CORS(_app_instance)
    return _app_instance

我已经尝试过这些解决方法,但都没效果:

  • 设置Python路径:export PYTHONPATH=$(pwd)/backend
  • 把整个tests文件夹移到app目录里
  • 在backend目录添加__init__.py,然后尝试用from backend.app.routes import dev_routes导入

备注:内容来源于stack exchange,提问作者football568

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 14:29:33