【发布时间】:2021-02-08 01:17:44
【问题描述】:
我确实有简单的FastAPI 应用程序,并且我使用 pip 和 venv 来管理环境。当我通过 uvicorn 安装包运行它时,我的导入不可见。它适用于python终端。
简化的文件夹结构: /venv /src 主文件 .. 要求.txt ..
requirements.txt
alembic==1.4.3
click==7.1.2
fastapi==0.61.1
FastAPI-SQLAlchemy==0.2.1
pydantic==1.6.1
SQLAlchemy==1.3.20
uvicorn==0.12.2
python-dotenv==0.14.0
在我将激活环境后在python shell中导入fastapi_sqlalchemy作品:
Python 3.8.5 (default, Aug 25 2020, 14:19:38)
[Clang 11.0.3 (clang-1103.0.32.62)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import fastapi_sqlalchemy
>>>
但是当我通过 uvicorn 运行 fastapi 时,应用程序会在 fastapi_sqlalchemy 导入时抛出错误。
uvicorn src.main:app --reload ✔ 16:58:54
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [40567] using statreload
3.8.5 (default, Aug 25 2020, 14:19:38)
[Clang 11.0.3 (clang-1103.0.32.62)]
Process SpawnProcess-1:
Traceback (most recent call last):
(... stacktrace here ...)
File "./src/main.py", line 8, in <module>
import fastapi_sqlalchemy
ModuleNotFoundError: No module named 'fastapi_sqlalchemy'
src/main.py
import uvicorn
from fastapi import FastAPI
from dotenv import load_dotenv
import sys
print(sys.version)
import fastapi_sqlalchemy
我不知道如何让这个库在运行 uvicorn/fastapi 应用程序的上下文中可见。
【问题讨论】:
-
uvicorn 是如何知道使用虚拟环境的?
-
我确实假设它确实在应该使用 venv 的终端运行时的上下文中运行。因此我希望它会看到导入,因为我可以在 python shell 中引用。
-
你是如何启用环境的?
-
不确定您的想法,彼得。我确实运行了 source venv/bin/activate 但不确定它会带来更多的上下文,正如我所说的 - 我在 python shell 中运行导入时没有问题。
-
嗯,到 src 同一个文件夹,像
src.main:app一样运行它