首页 > 解决方案 > 如何导入 FastAPI 应用程序文件夹以满足 pycharm 和 pylint?

问题描述

我试图找出在我的项目中管理相对导入和绝对导入的最佳方法,以便来自 pylint、pytest、vscode 和 pycharm 的测试和 linting 工具都满意,以便应用程序在生产中正确运行。

我没有打包这个应用程序,setup.py因为它安装在一个 docker 镜像中并从它的工作目录运行。我的项目目录结构是这样的:

app
 ┣ app
 ┃ ┣ static
 ┃ ┃ ┗ myfrontend.js
 ┃ ┣ templates
 ┃ ┃ ┗ index.html
 ┃ ┣ tests
 ┃ ┃ ┣ __init__.py
 ┃ ┃ ┗ test_server.py
 ┃ ┣ __init__.py
 ┃ ┣ main.py
 ┃ ┗ utils.py
 ┣ Dockerfile
 ┗ requirements.txt

app/app/main.py进口是:

from app.utils import prepare_file

app = FastAPI()

app/app/tests/test_server.py进口是:

from app.main import app
from app.utils import prepare_file

整个事情是从tiangolo/uvicorn-gunicorn-fastapi 构建的 docker映像运行的,方法是复制文件并设置工作目录:

COPY ./app/app /app/app/
WORKDIR /app

这适用于 VSCode linting 和测试,以及 QA 工具链:

pylint -E app/app # processes with no errors
pytest app/app/tests # correctly runs tests
docker build . -f app/Dockerfile -t myapp && docker container run myapp # app runs

但是,PyCharm 对导入感到窒息:

Unresolved reference 'app'
Cannot find reference 'main' in 'imported module app'
Cannot find reference 'utils' in 'imported module app'

PyCharm 项目有两个子模块(具有核心“业务逻辑”的库和包装它的 webapp)。

Pycharm 可以通过更改app/app/main.py为:

from ..app.utils import prepare_file

app/app/tests/test_server.py

from ...app.main import app
from ...app.utils import prepare_file

但这会触发 pylint:

$ pylint -E app/app
************* Module app.main
app/app/main.py:18:0: E0402: Attempted relative import beyond top-level package (relative-beyond-top-level)
************* Module app.tests.test_server
app/app/tests/test_server.py:2:0: E0402: Attempted relative import beyond top-level package (relative-beyond-top-level)
app/app/tests/test_server.py:3:0: E0402: Attempted relative import beyond top-level package (relative-beyond-top-level)

我能想到两种可能的解释:

  1. PyCharm 有一个隐藏在某处的开关,需要翻转以使其兼容。我尝试标记app/app为“源根”,但没有帮助。
  2. 整个方法违反了 python web 应用程序的正确结构,整个事情都应该重组。

你怎么看?这是 PyCharm 兼容性问题吗?还是方形钉圆形整体设计问题?

标签: pythonpycharmpython-importfastapipylint

解决方案


解决方案:标记app为“sources root” not app/app。然后 pycharm 会看到其他 linter 看到的内容。

感谢@lsabi 和@mx0 的指点。


推荐阅读