TestDriven.io 教程 "Scalable FastAPI Applications on AWS":第 1 部分 API 请求通话 Endpont 代码不起作用

TestDriven.io Tutorial "Scalable FastAPI Applications on AWS": Part 1 API Request a Talk Endpont code doesn't work

我正在学习 TestDriven.io 教程“AWS 上可快速扩展的API 应用程序”。在第 1 部分的“API”章中,“Request a Talk”-“Endpoint”下的代码失败,但未达到预期。这是页面的link:

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_app/main.py 文件),我在以下几行中收到错误:

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

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

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

给出的示例不适用于 FastAPI,它适用于 Flask(来自 current version of Flask's examples on configuration handling):

app = Flask(__name__)
app.config['TESTING'] = True

在 FastAPI 中,如有必要,您通常会覆盖显式依赖项,and/or 使用环境变量更改 pydantic 的 BaseSettings 对象的配置。

Using BaseSettings:

from pydantic import BaseSettings


class Settings(BaseSettings):
    app_name: str = "Awesome API"
    admin_email: str
    items_per_user: int = 50

然后您可以使用 APP_NAMEADMIN_EMAIL 作为环境变量覆盖特定的配置设置。您还可以在需要时将设置对象作为依赖项注入,然后在测试时覆盖该依赖项。

Overriding a dependency:

async def override_dependency(q: Optional[str] = None):
    return {"q": q, "skip": 5, "limit": 10}


app.dependency_overrides[common_parameters] = override_dependency

鉴于您已经提到的错误以及给出的示例似乎与完全不同于 FastAPI 的东西相关,我会谨慎地相信该来源 material(link 在后面一个登录表格,所以它不公开。

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

from web_app.main import app


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

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