国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

【Python開發(fā)】FastAPI 11:構(gòu)建多文件應用

這篇具有很好參考價值的文章主要介紹了【Python開發(fā)】FastAPI 11:構(gòu)建多文件應用。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

以往的文件都是將對外接口寫在一個文件里邊,而作為應用來說,接口是不可避免分散到多個文件中的,比如某文件負責注冊登錄模塊,某文件負責內(nèi)管模塊,某文件負責業(yè)務模塊等。FastAPI 也提供了APIRouter 這一工具來進行靈活構(gòu)建應用,本文將是它的示例。

目錄

1?APIRouter

1.1?APIRouter 使用

1.2 其他模塊的引入

2 app 項目示例

2.1 文件結(jié)構(gòu)

2.2 其他 文件

2.3 main 文件

2.4 API 文檔


???源碼地址:

https://gitee.com/yinyuu/fast-api_study_yinyu

1?APIRouter

大家可以看到,前邊的示例均是以?app = FastAPI() 作為路由,但是它只適合小項目,如果接口按模塊進行劃分就不滿足了。而?APIRouter 正實現(xiàn)了接口按模塊的功能,以使其井井有條。

1.1?APIRouter 使用

類似?app = FastAPI()

from fastapi import APIRouter #導入 APIRouter

router = APIRouter()

@router.get("/users/", tags=["users"])
async def read_users():
    return [{"username": "Rick"}, {"username": "Morty"}]

可以將 APIRouter 視為一個小號 FastAPI 類,所有相同的選項都得到支持,比如 parameters、responses、dependencies、tags 等等。

此示例中,該變量被命名為 router,但你可以根據(jù)你的想法自由命名。

1.2 其他模塊的引入

類似 FastAPI ,我們還可以通過 prefix、tagsdependencies responses 等參數(shù)來減少重復代碼和增加效率。比如有兩個接口:

  • /items/
  • /items/{item_id}

他們的路徑前綴一樣,那么我們通過以下方式簡化代碼:

  • prefix:/items,前綴,不能以?/?作為結(jié)尾,不然回合路徑重合
  • tags:items 標簽,主要在 api 文檔中用于分類
  • responses:額外的響應模型,所有接口都將擁有
  • dependencies:依賴,比如 get_token_header 依賴項。
from fastapi import APIRouter, Depends, HTTPException
 
from ..dependencies import get_token_header #通過 .. 對依賴項使用了相對導入,具體代碼可看第二章

router = APIRouter(
    prefix="/items",
    tags=["items"],
    dependencies=[Depends(get_token_header)],
    responses={404: {"description": "Not found"}},
)

@router.get("/")
async def read_items():
    return fake_items_db

@router.get("/{item_id}")
async def read_item(item_id: str):
    if item_id not in fake_items_db:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"name": fake_items_db[item_id]["name"], "item_id": item_id}

最終結(jié)果是項目相關(guān)的路徑現(xiàn)在為:

  • /items/
  • /items/{item_id}

2 app 項目示例

接下來以 app 項目為例,展示一下多文件應用的構(gòu)建。

2.1 文件結(jié)構(gòu)

???結(jié)構(gòu)如下:
【Python開發(fā)】FastAPI 11:構(gòu)建多文件應用

app 目錄包含了所有內(nèi)容,他是一個?Python 包:

  • app/main.pymain 模塊,也是項目的主文件,或者說啟動類
  • app/dependencies.py:存放依賴項
  • app/routers/ :Python 子包:
    • app/routers/items.py:存放 ietms 相關(guān)接口
    • app/routers/users.py:存放 users?相關(guān)接口
  • app/internal/ :Python 子包:
    • app/internal/admin.py:內(nèi)管相關(guān)接口

2.2 其他 文件

???dependencies.py

依賴項相關(guān)方法,驗證請求體和 token ~

from fastapi import Header, HTTPException

async def get_token_header(x_token: str = Header()):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")

async def get_query_token(token: str):
    if token != "jessica":
        raise HTTPException(status_code=400, detail="No Jessica token provided")

???items.py

from fastapi import APIRouter, Depends, HTTPException

from ..dependencies import get_token_header

router = APIRouter(
    prefix="/items",
    tags=["items"],
    dependencies=[Depends(get_token_header)],
    responses={404: {"description": "Not found111"}},
)

fake_items_db = {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}}

@router.get("/")
async def read_items():
    return fake_items_db

@router.get("/{item_id}")
async def read_item(item_id: str):
    if item_id not in fake_items_db:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"name": fake_items_db[item_id]["name"], "item_id": item_id}

@router.put(
    "/{item_id}",
    tags=["custom"],
    responses={403: {"description": "Operation forbidden"}},
)
async def update_item(item_id: str):
    if item_id != "plumbus":
        raise HTTPException(
            status_code=403, detail="You can only update the item: plumbus"
        )
    return {"item_id": item_id, "name": "The great Plumbus"}

???users.py

from fastapi import APIRouter

router = APIRouter()

@router.get("/users/", tags=["users"])
async def read_users():
    return [{"username": "Rick"}, {"username": "Morty"}]

@router.get("/users/me", tags=["users"])
async def read_user_me():
    return {"username": "fakecurrentuser"}

@router.get("/users/{username}", tags=["users"])
async def read_user(username: str):
    return {"username": username}

???users.py

from fastapi import APIRouter

router = APIRouter()

@router.post("/")
async def update_admin():
    return {"message": "Admin getting schwifty"}

以上接口文件均使用 APIRouter ,最后將調(diào)用給 main 文件以供匯總。

2.3 main 文件

這里你導入并使用 FastAPI 類,是應用程序中將所有內(nèi)容聯(lián)結(jié)在一起的主文件。?

from fastapi import Depends, FastAPI

from .dependencies import get_query_token, get_token_header
from .internal import admin
from .routers import items, users

app = FastAPI(dependencies=[Depends(get_query_token)])

app.include_router(users.router)
app.include_router(items.router)
app.include_router( #依舊可自定義參數(shù)
    admin.router,
    prefix="/admin",
    tags=["admin"],
    dependencies=[Depends(get_token_header)],
    responses={418: {"description": "I'm a teapot"}},
)

@app.get("/")
async def root():
    return {"message": "Hello Bigger Applications!"}


if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

???導入模塊

比如:

from .routers import items, users
  • 這表示從該模塊(app/main.py 文件)所在的同一個包(app/ 目錄)
  • 尋找 routers 子包(位于 app/routers/ 的目錄)...
  • 從該包中,導入子模塊 items (位于 app/routers/items.py 的文件) 以及 users (位于 app/routers/users.py 的文件)...

items 模塊將具有一個 router 變量(items.router)。

相對導入:from .routers import items, users

絕對導入:from app.routers import items, users

???app.include_router

app.include_router(users.router)
app.include_router(items.router)

使用 app.include_router(),我們可以將每個 APIRouter 添加到主 FastAPI 應用程序中。 它將包含來自該路由器的所有路由作為其一部分。

官方:包含路由器時,你不必擔心性能問題。 這將花費幾微秒時間,并且只會在啟動時發(fā)生。 因此,它不會影響性能。?

2.4 API 文檔

啟動 main 文件,訪問?http://127.0.0.1:8000/docs,即可看到使用了正確路徑(和前綴)和正確標簽的自動化 API 文檔,包括了來自所有子模塊的路徑:

【Python開發(fā)】FastAPI 11:構(gòu)建多文件應用

由于 fastapi 內(nèi)置的接口文檔使用的外網(wǎng)的 cdn,所以可能導致頁面卡死,接口文檔顯示空白,解決辦法可參考:https://blog.csdn.net/m0_52726759/article/details/124854070。文章來源地址http://www.zghlxwxcb.cn/news/detail-497742.html

到了這里,關(guān)于【Python開發(fā)】FastAPI 11:構(gòu)建多文件應用的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務器費用

相關(guān)文章

  • MemFire教程|FastAPI+MemFire Cloud+LangChain開發(fā)ChatGPT應用-Part2

    MemFire教程|FastAPI+MemFire Cloud+LangChain開發(fā)ChatGPT應用-Part2

    上篇文章我們講解了使用FastAPI+MemFire Cloud+LangChain進行GPT知識庫開發(fā)的基本原理和關(guān)鍵路徑的代碼實現(xiàn)。目前完整的實現(xiàn)代碼已經(jīng)上傳到了github,感興趣的可以自己玩一下: https://github.com/MemFire-Cloud/memfirecloud-qa 目前代碼主要完成了如下一些基本功能: 使用FastAPI作為Web服務端

    2024年02月14日
    瀏覽(22)
  • 【Python開發(fā)】FastAPI 10:SQL 數(shù)據(jù)庫操作

    【Python開發(fā)】FastAPI 10:SQL 數(shù)據(jù)庫操作

    在 FastAPI 中使用 SQL 數(shù)據(jù)庫可以使用多個 ORM 工具,例如 SQLAlchemy、Tortoise ORM 等,類似 Java 的 Mybatis 。這些?ORM 工具可以幫助我們方便地與關(guān)系型數(shù)據(jù)庫進行交互,如 MySQL 、PostgreSQL等。本篇文章將介紹如何使用 SQLAlchemy 來完成數(shù)據(jù)庫操作,以便讓我們在 FastAPI 項目中方便地進

    2024年02月14日
    瀏覽(25)
  • python三大開發(fā)框架django、 flask 和 fastapi 對比

    python三大開發(fā)框架django、 flask 和 fastapi 對比

    本文講述了什么啟發(fā)了 FastAPI 的誕生,它與其他替代框架的對比,以及從中汲取的經(jīng)驗。 如果不是基于前人的成果,F(xiàn)astAPI 將不會存在。在 FastAPI 之前,前人已經(jīng)創(chuàng)建了許多工具 。 幾年來,我一直在避免創(chuàng)建新框架。首先,我嘗試使用許多不同的框架,插件和工具來解決

    2024年02月10日
    瀏覽(26)
  • 【Python開發(fā)】FastAPI 09:middleware 中間件及跨域

    【Python開發(fā)】FastAPI 09:middleware 中間件及跨域

    FastAPI?提供了一些中間件來增強它的功能,類似于 Spring 的切面編程,中間件可以在請求處理前或處理后執(zhí)行一些操作,例如記錄日志、添加請求頭、鑒權(quán)等,跨域也是 FastAPI?中間件的一部分。 目錄 1 中間件 1.1?創(chuàng)建中間件 1.2 使用中間件? 2 跨域 2.1 跨域詳解 2.2 使用 CORSM

    2024年02月09日
    瀏覽(23)
  • ChatGPT Plugin開發(fā)setup - Java(Spring Boot) Python(fastapi)

    記錄一下快速模板,整體很簡單,如果不接auth,只需要以下: 提供一個 /.well-known/ai-plugin.json 接口,返回openAI所需要的格式 提供openAPI規(guī)范的文檔 CORS設置 其他的和普通的web開發(fā)類似. 本地開發(fā)就直接使用localhost即可,前幾天官方localhost無法聯(lián)通,最近應該修復了. 要讓GPT更好理解接口

    2024年02月04日
    瀏覽(16)
  • FastAPI + NGINX + Gunicorn:一步一步教你部署一個高性能的Python網(wǎng)頁應用

    FastAPI + NGINX + Gunicorn:一步一步教你部署一個高性能的Python網(wǎng)頁應用

    部署一個 FastAPI 應用到你的服務器是一項復雜的任務。如果你對 NGINX 、 Gunicorn 和 Uvicorn 這些技術(shù)不熟悉,可能會浪費大量的時間。如果你是剛接觸 Python 語言不久或者希望利用 Python 構(gòu)建自己的Web應用程序,本文的內(nèi)容可能會讓你第一次部署時更節(jié)省時間。 FastAPI 是用于開發(fā)

    2024年02月05日
    瀏覽(26)
  • 畢業(yè)設計:Vue3+FastApi+Python+Neo4j實現(xiàn)主題知識圖譜網(wǎng)頁應用——前言

    畢業(yè)設計:Vue3+FastApi+Python+Neo4j實現(xiàn)主題知識圖譜網(wǎng)頁應用——前言

    資源鏈接:https://download.csdn.net/download/m0_46573428/87796553 前言:畢業(yè)設計:Vue3+FastApi+Python+Neo4j實現(xiàn)主題知識圖譜網(wǎng)頁應用——前言_人工智能技術(shù)小白修煉手冊的博客-CSDN博客 首頁與導航:畢業(yè)設計:Vue3+FastApi+Python+Neo4j實現(xiàn)主題知識圖譜網(wǎng)頁應用——前端:首頁與導航欄_人工智

    2024年02月14日
    瀏覽(28)
  • FastAPI 構(gòu)建 API 高性能的 web 框架(二)

    上一篇 FastAPI 構(gòu)建 API 高性能的 web 框架(一)是把LLM模型使用Fastapi的一些例子,本篇簡單來看一下FastAPI的一些細節(jié)。 有中文官方文檔:fastapi中文文檔 假如你想將應用程序部署到生產(chǎn)環(huán)境,你可能要執(zhí)行以下操作: 并且安裝uvicorn來作為服務器: 然后對你想使用的每個可選

    2024年02月12日
    瀏覽(25)
  • FastAPI和Flask:構(gòu)建RESTful API的比較分析

    FastAPI和Flask:構(gòu)建RESTful API的比較分析

    Python 是一種功能強大的編程語言,廣泛應用于 Web 開發(fā)領(lǐng)域。 FastAPI ?和 Flask 是 Python Web 開發(fā)中最受歡迎的兩個框架。本文將對 FastAPI 和 Flask 進行綜合對比,探討它們在語法和表達能力、生態(tài)系統(tǒng)和社區(qū)支持、性能和擴展性、開發(fā)工具和調(diào)試支持、安全性和穩(wěn)定性、學習曲線

    2024年02月13日
    瀏覽(26)
  • FastAPI 構(gòu)建 API 高性能的 web 框架(一)

    FastAPI 構(gòu)建 API 高性能的 web 框架(一)

    如果要部署一些大模型一般langchain+fastapi,或者fastchat, 先大概了解一下fastapi,本篇主要就是貼幾個實際例子。 官方文檔地址: https://fastapi.tiangolo.com/zh/ 來源:大語言模型工程化服務系列之五-------復旦MOSS大模型fastapi接口服務 服務端代碼: api啟動后,調(diào)用代碼: 來源: 大語

    2024年02月13日
    瀏覽(27)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包