AttributeError:“FastAPI”对象没有属性“config”

问题描述 投票:0回答:2

我正在学习 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”

当我将其更改为 import web_app.main 时(这更有意义,因为实际上有一个 web_app/main.py 文件),我在以下几行中收到错误:

@pytest.fixture
def client():
    app.config["TESTING"] = True

现在的错误是“AttributeError:'FastAPI'对象没有属性'config'”。

到目前为止,还有其他人完成了本教程并遇到了同样的问题吗?

python fastapi
2个回答
0
投票

给出的示例不是针对 FastAPI,而是针对 Flask(它来自 当前版本的 Flask 配置处理示例):

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 完全不同的内容相关,我对信任该源材料持谨慎态度(链接位于登录表单后面,因此不公开)。


0
投票

MatsLindh:是的 - 通过用以下代码替换代码,我能够让它工作:

from web_app.main import app


@pytest.fixture
def client():
    return TestClient(app)

这对应于 FastAPI 中应该如何完成

© www.soinside.com 2019 - 2024. All rights reserved.