我正在学习TestDriven.io教程“AWS上的可伸缩FastAPI应用程序”。在第1部分的"API“一章中,"Request a Talk”- "Endpoint“下的代码失败了,但并不像预期的那样。这是指向该页面的链接:
https://testdriven.io/courses/scalable-fastapi-aws/api-endpoints/
文件是test_app.py,有问题的行是:
from web_app.app import app运行此文件时,错误为"No module named web_app.app“
当我将其改为导入web_app.main时(这更有意义,因为实际上有一个web/main.py文件),我在以下几行得到一个错误:
@pytest.fixture
def client():
app.config["TESTING"] = True现在的错误是“配置:'FastAPI‘对象没有’AttributeError‘属性”。
到目前为止,还有没有其他人完成了本教程,并遇到了同样的问题?
发布于 2021-10-06 14:25:58
给出的示例不是针对FastAPI的,而是针对Flask的(来自current version of Flask's examples on configuration handling):
app = Flask(__name__)
app.config['TESTING'] = True在FastAPI中,如果有必要,您通常会覆盖显式依赖项,并且/或者使用环境变量来更改pydantic的BaseSettings对象中的配置。
from pydantic import BaseSettings
class Settings(BaseSettings):
app_name: str = "Awesome API"
admin_email: str
items_per_user: int = 50然后,您可以使用APP_NAME或ADMIN_EMAIL作为环境变量来覆盖特定的配置设置。您还可以在需要时将设置对象作为依赖项注入,然后在测试时重写该依赖项。
async def override_dependency(q: Optional[str] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency考虑到您已经提到的错误,以及给出的示例似乎与FastAPI完全不同,我会谨慎地相信这些原始材料(链接在表单中的符号后面,所以它不是公开可用的)。
发布于 2021-10-08 12:13:43
MatsLindh:是的-通过用下面的代码替换代码,我能够让它工作:
from web_app.main import app
@pytest.fixture
def client():
return TestClient(app)这与在FastAPI中应该如何完成操作相对应
https://stackoverflow.com/questions/69467455
复制相似问题