搜索
首页后端开发Python教程为什么应该使用单个 FastAPI 应用程序和 TestClient 实例

Why You Should Use a Single FastAPI App and TestClient Instance

在 FastAPI 开发中,特别是对于大型项目,在整个项目中使用单个 FastAPI 应用程序实例和单个 TestClient 实例对于保持一致性、优化性能和确保可靠性至关重要。 让我们研究一下这种最佳实践背后的原因并探索实际示例。

1.应用程序范围内的一致性

创建多个 FastAPI 应用实例可能会导致不一致。每个实例都拥有自己的内部状态、中间件配置和依赖关系管理。 跨多个实例共享有状态数据(例如内存存储或数据库连接)可能会导致不可预测的行为和错误。

2.增强的性能

每个 TestClient 实例建立自己的 HTTP 连接并初始化依赖项。使用单个 TestClient 可最大限度地减少开销,从而加快测试执行速度。

3.防止初始化问题

FastAPI 应用程序经常在启动期间初始化资源,包括数据库连接或后台任务。 多个实例可能会导致冗余初始化或资源冲突。

实践代码示例

正确方法:单个应用程序和 TestClient

from fastapi import FastAPI, Depends
from fastapi.testclient import TestClient

# Single FastAPI app instance
app = FastAPI()

# Simple in-memory database
database = {"items": []}

# Dependency function
def get_database():
    return database

@app.post("/items/")
def create_item(item: str, db: dict = Depends(get_database)):
    db["items"].append(item)
    return {"message": f"Item '{item}' added."}

@app.get("/items/")
def list_items(db: dict = Depends(get_database)):
    return {"items": db["items"]}

# Single TestClient instance
client = TestClient(app)

# Test functions
def test_create_item():
    response = client.post("/items/", json={"item": "foo"})
    assert response.status_code == 200
    assert response.json() == {"message": "Item 'foo' added."}

def test_list_items():
    response = client.get("/items/")
    assert response.status_code == 200
    assert response.json() == {"items": ["foo"]}

错误方法:多个实例

# Incorrect: Multiple app instances
app1 = FastAPI()
app2 = FastAPI()

# Incorrect: Multiple TestClient instances
client1 = TestClient(app1)
client2 = TestClient(app2)

# Problem: State changes in client1 won't affect client2

多实例的常见问题

  1. 不一致的状态:共享状态(如数据库)在不同的应用程序实例之间独立运行。
  2. 冗余依赖项初始化:数据库连接等依赖项可能会多次初始化,可能导致资源耗尽。
  3. 重叠的启动/关闭事件:多个应用实例独立触发启动和关闭事件,导致不必要或冲突的行为。

最佳实践

可重用性项目结构

在单独的文件(例如 app.py)中创建 FastAPI 应用程序并在需要时导入。

# app.py
from fastapi import FastAPI

app = FastAPI()
# Add your routes here
# main.py
from fastapi.testclient import TestClient
from app import app

client = TestClient(app)

利用共享实例的 pytest 装置

pytest 装置有效管理共享资源,例如 TestClient:

import pytest
from fastapi.testclient import TestClient
from app import app

@pytest.fixture(scope="module")
def test_client():
    client = TestClient(app)
    yield client  # Ensures proper cleanup
def test_example(test_client):
    response = test_client.get("/items/")
    assert response.status_code == 200

相关文档

  • Starlette 测试客户端
  • 使用 FastAPI 进行测试
  • pytest 装置

通过遵守这些准则,您的 FastAPI 项目将更加一致、高效且更易于维护。


肖恩·杜塔拍摄:https://www.php.cn/link/e2d083a5fd066b082d93042169313e21

以上是为什么应该使用单个 FastAPI 应用程序和 TestClient 实例的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
在Python阵列上可以执行哪些常见操作?在Python阵列上可以执行哪些常见操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些类型的应用程序中,Numpy数组常用?在哪些类型的应用程序中,Numpy数组常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什么时候选择在Python中的列表上使用数组?您什么时候选择在Python中的列表上使用数组?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。

您如何在python列表中访问元素?您如何在python列表中访问元素?Apr 26, 2025 am 12:03 AM

toAccesselementsInapythonlist,useIndIndexing,负索引,切片,口头化。1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Python的科学计算中如何使用阵列?Python的科学计算中如何使用阵列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何处理同一系统上的不同Python版本?您如何处理同一系统上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

与标准Python阵列相比,使用Numpy数组的一些优点是什么?与标准Python阵列相比,使用Numpy数组的一些优点是什么?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具