python - 如何导入 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)
我能想到两种可能的解释:
- PyCharm 有一个隐藏在某处的开关,需要翻转以使其兼容。我尝试标记
app/app
为“源根”,但没有帮助。 - 整个方法违反了 python web 应用程序的正确结构,整个事情都应该重组。
你怎么看?这是 PyCharm 兼容性问题吗?还是方形钉圆形整体设计问题?
解决方案
解决方案:标记app
为“sources root” not app/app
。然后 pycharm 会看到其他 linter 看到的内容。
感谢@lsabi 和@mx0 的指点。
推荐阅读
- node.js - 尽管在 OS X 64 位上使用 4.12 版进行了重建和卸载,Node Sass 仍不支持当前环境
- c# - 在 C# 的线程中以编程方式复制 Excel 文件时如何修复拒绝访问错误
- laravel - 在 vue 组件中执行编辑功能时如何显示数据库中的特定图像?
- shell - awk 获取特殊字符之间的特定单词
- c++ - 为什么这个参数包不能直接解包到向量初始化列表中?
- angular - 清理组件时出错 this._app.unregisterRootNav 不是 NavControllerBase.destroy 的函数
- python - 如何获取选定复选框的总和并将选定项目保存在数据库 mysql 中
- php - 修剪/减少PHP中的多维数组到一定深度
- hyperledger-fabric-ca - 如何远程访问 Fabric-ca 服务器?
- angular - 需要为许多属性中的特定属性应用管道