產品比較

FastAPI Python(它如何為開發者運作)

發佈 2024年9月29日
分享:

介紹

FastAPI是一個以 Python 構建 API 的現代高性能網路框架。 它被設計為易於使用和學習,同時提供強大的功能,如自動驗證、序列化和自動交互式 API 文件。 此外,它可以與任何模板引擎一起使用,並允許您使用項目所需的任何預設模板配置。

讓我們深入了解的細節 FastAPI、其功能,以及如何有效使用。 稍後在本文中,我們還將探討 IronPDF 來自的 PDF 生成 Python 套件 IronSoftware.

FastAPI 的主要功能

  1. 高效能:FastAPI 是目前最快的 Python 框架之一,與 Node.js 和 Go 相當,這要歸功於其在網路部分使用 Starlette 和在數據部分使用 Pydantic。

  2. 易於使用:它被設計為直觀並減少閱讀文檔所花費的時間。 該框架利用標準的 Python 類型提示進行數據驗證和序列化。

  3. 自動互動式文件:FastAPI 使用 OpenAPI 和 JSON Schema 自動生成互動式 API 文件,可透過 /docs 存取。 (Swagger UI) 和 /redoc (ReDoc) 互動式 API 文件升級意味著這些文件會自動更新。 替代 API 文件升級也將反映這一點。

  4. 編輯器支援:在如 VS Code 等編輯器中,提供出色的程式碼自動完成功能和類型檢查支持,加快開發速度並減少錯誤。

  5. 符合標準:它是基於 (完全相容於) API 開放標準:OpenAPI 和 JSON Schema。

安裝

您可以安裝 FastAPI 和 Uvicorn (ASGI 伺服器) 使用 pip:

pip install fastapi
pip install "uvicorn[standard]"
pip install fastapi
pip install "uvicorn[standard]"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'pip install fastapi pip install "uvicorn[standard]"
VB   C#

建立您的第一個 FastAPI 應用程式

以下是一個簡單的示例,讓您開始使用 FastAPI 並透過用戶界面公開 Python 數據:

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
    return {"Hello": "World"}
@app.get("/items/{item_id}") # with query parameters
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
    return {"Hello": "World"}
@app.get("/items/{item_id}") # with query parameters
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}
from fastapi import FastAPI app = FastAPI() app.get("/") def read_root(): Return
If True Then
	"Hello": "World"
End If
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'@app.@get("/items/{item_id}") # @with query parameters def read_item(item_id: int, q: str = None): Return
'{
''INSTANT VB TODO TASK: The following line uses invalid syntax:
''	"item_id": item_id, "q": q}
VB   C#

要運行應用程式,請使用 Uvicorn:

uvicorn main:app --reload
uvicorn main:app --reload
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'uvicorn main:app --reload
VB   C#

此命令將啟動開發伺服器並自動重新載入以響應程式碼變更。 您可以在 http://127.0.0.1:8000/docs 訪問互動式 API 文件。

進階功能

FastAPI 支援多樣的高階功能,非常適合用於複雜應用程式:

  1. 依賴注入:FastAPI 提供了強大的依賴注入系統,可讓您乾淨且高效地管理依賴項。

  2. 背景任務:您可以定義在回應返回後執行的背景任務,這對於像發送電子郵件或處理資料等任務非常有用。

  3. WebSockets:FastAPI 支援 WebSockets,允許客戶端和伺服器之間進行即時通訊。

  4. 安全:FastAPI 包含用於處理安全性的工具,包括 OAuth2、JWT 令牌等。

  5. 資料庫整合:FastAPI 可以使用 SQLAlchemy 或 Tortoise-ORM 等庫輕鬆整合資料庫。

範例:建立 CRUD API

讓我們建立一個簡單的 CRUD (建立, 讀取, 更新, 刪除) 管理項目的 API。

  1. 定義資料模型
from pydantic import BaseModel
class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
from pydantic import BaseModel
class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'from pydantic import BaseModel class Item(BaseModel): name: str description: str = None price: float tax: float = None
VB   C#
  1. 建立 FastAPI 應用程式
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {}
@app.post("/items/")
def create_item(item: Item):
    item_id = len(items) + 1
    items[item_id] = item
    return item
@app.get("/items/{item_id}") # optional str query parameter
def read_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return items[item_id]
@app.put("/items/{item_id}") # with path parameters
def update_item(item_id: int, item: Item):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    items[item_id] = item
    return item
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    del items[item_id]
    return {"message": "Item deleted"}
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {}
@app.post("/items/")
def create_item(item: Item):
    item_id = len(items) + 1
    items[item_id] = item
    return item
@app.get("/items/{item_id}") # optional str query parameter
def read_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return items[item_id]
@app.put("/items/{item_id}") # with path parameters
def update_item(item_id: int, item: Item):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    items[item_id] = item
    return item
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    del items[item_id]
    return {"message": "Item deleted"}
404, detail="Item not found"
status_code=404, detail
404, detail="Item not found"
status_code=404, detail
404, detail="Item not found"
status_code=404, detail
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: from fastapi import FastAPI, HTTPException app = FastAPI() items = {} @app.post("/items/") def create_item(item: Item): item_id = len(items) + 1 items[item_id] = item return item @app.get("/items/{item_id}") # optional str query parameter def read_item(item_id: int): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") return items[item_id] @app.put("/items/{item_id}") # with path parameters def update_item(item_id: int, item: Item): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") items[item_id] = item return item @app.delete("/items/{item_id}") def delete_item(item_id: int): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") del items[item_id] return
item Return item app.get("/items/{item_id}") # [optional] str query parameter def read_item(item_id:= Integer): if item_id [not] in items: raise HTTPException(status_code) Return items(item_id) app.put("/items/{item_id}") # [with] path parameters def update_item(item_id: Integer, item: Item): if item_id [not] in items: raise HTTPException(status_code) items(item_id) = item Return item app.delete("/items/{item_id}") def delete_item(item_id: Integer): if item_id [not] in items: raise HTTPException(status_code) del items(item_id) Return
If True Then
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: from fastapi import FastAPI, HTTPException app = FastAPI() items = {} @app.post("/items/") def create_item(item: Item): item_id = len(items) + 1 items[item_id] = item return item @app.get("/items/{item_id}") # optional str query parameter def read_item(item_id: int): if item_id not in items: raise HTTPException(status_code) return items[item_id] @app.put("/items/{item_id}") # with path parameters def update_item(item_id: int, item: Item): if item_id not in items: raise HTTPException(status_code) items[item_id]
len(items) + 1 items(item_id) = item Return item app.get("/items/{item_id}") # [optional] str query parameter def read_item(item_id:= Integer): if item_id [not] in items: raise HTTPException(status_code) Return items(item_id) app.put("/items/{item_id}") # [with] path parameters def update_item(item_id: Integer, item: Item): if item_id [not] in items: raise HTTPException(status_code) items(item_id)
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: from fastapi import FastAPI, HTTPException app = FastAPI() items = {} @app.post("/items/") def create_item(item: Item): item_id = len(items) + 1 items[item_id]
{} app.post("/items/") def create_item(item:= Item): item_id = len(items) + 1 items(item_id)
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: from fastapi import FastAPI, HTTPException app = FastAPI() items = {} @app.post("/items/") def create_item(item: Item): item_id
FastAPI() items = {} app.post("/items/") def create_item(item:= Item): item_id
from fastapi import FastAPI, HTTPException app = FastAPI() items
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'	"message": "Item deleted"}
VB   C#

介紹 IronPDF

FastAPI Python(對開發人員的運作方式):圖 1

IronPDF 是一個強大的 Python 函式庫,用於從 HTML、CSS、圖像和 JavaScript 創建、編輯和簽署 PDF。 它提供商用級性能且佔用較低的記憶體資源。 主要功能包括:

HTML 轉 PDF

將 HTML 文件、HTML 字串和 URL 轉換為 PDF。 例如,使用 Chrome PDF 渲染器將網頁呈現為 PDF。

跨平台支援

兼容各種 .NET 平台,包括 .NET Core、.NET Standard 和 .NET Framework。 它支援 Windows、Linux 和 macOS。

編輯和簽署

設置屬性、通過密碼和權限添加安全性,並對您的PDF應用數字簽名。

頁面模板和設置

自訂 PDF 的頁眉、頁腳、頁碼和可調整的邊距。 支持響應式版面和自訂紙張尺寸。

標準合規性

遵循 PDF 標準,如 PDF/A 和 PDF/UA。 支持 UTF-8 字符編碼並處理資產,例如圖像、CSS 和字體。

使用 IronPDF 和 FastAPI 生成 PDF 文件

pip install fastapi
pip install ironPDF
pip install fastapi
pip install ironPDF
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'pip install fastapi pip install ironPDF
VB   C#
from fastapi import FastAPI
from fastapi.responses import FileResponse
from ironpdf import * 
# Apply your license key
License.LicenseKey = "key"
app = FastAPI()
@app.get("/")
def read_root():
    return {"Hello": "IronPDF"}
@app.get("/items/{item_id}") # with query parameters
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}
@app.get("/pdf")
async def get_pdf(greet1: str = None,greet2: str = None):
    renderer = ChromePdfRenderer()
# Create a PDF from a HTML string using Python
    content = "<h1>Document Generated using IronPDF with fastapi GET</h1>"
    content += "<p> Demonstrate PDF generation using User Inputs"+"</p>"
    content += "<p>"+f"Greetings from: {greet1}"+"</p>"
    content += "<p>"+f"And Greetings from: {greet2}"+"</p>"
    pdf = renderer.RenderHtmlAsPdf(content)
    # Export to a file or Stream
    pdf.SaveAs("fastapi.pdf") 
    # To view the file in the browser, use "inline" for the media_type
    headers = {
        "Content-Disposition": "inline; filename=sample.pdf"
    }  
    # Create a FileResponse object with the file path, media type and headers
    response = FileResponse("fastapi.pdf", media_type="application/pdf", headers=headers)
    # Return the FileResponse object
    return response
from fastapi import FastAPI
from fastapi.responses import FileResponse
from ironpdf import * 
# Apply your license key
License.LicenseKey = "key"
app = FastAPI()
@app.get("/")
def read_root():
    return {"Hello": "IronPDF"}
@app.get("/items/{item_id}") # with query parameters
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}
@app.get("/pdf")
async def get_pdf(greet1: str = None,greet2: str = None):
    renderer = ChromePdfRenderer()
# Create a PDF from a HTML string using Python
    content = "<h1>Document Generated using IronPDF with fastapi GET</h1>"
    content += "<p> Demonstrate PDF generation using User Inputs"+"</p>"
    content += "<p>"+f"Greetings from: {greet1}"+"</p>"
    content += "<p>"+f"And Greetings from: {greet2}"+"</p>"
    pdf = renderer.RenderHtmlAsPdf(content)
    # Export to a file or Stream
    pdf.SaveAs("fastapi.pdf") 
    # To view the file in the browser, use "inline" for the media_type
    headers = {
        "Content-Disposition": "inline; filename=sample.pdf"
    }  
    # Create a FileResponse object with the file path, media type and headers
    response = FileResponse("fastapi.pdf", media_type="application/pdf", headers=headers)
    # Return the FileResponse object
    return response
#Apply your license key
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: from fastapi import FastAPI from fastapi.responses import FileResponse from ironpdf import * License.LicenseKey = "key" app = FastAPI() @app.get("/") def read_root(): return
"key" app = FastAPI() app.get("/") def read_root(): Return
If True Then
From fastapi import FastAPI From fastapi.responses import FileResponse From ironpdf import * License.LicenseKey = "key" app
	"Hello": "IronPDF"
End If
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'@app.@get("/items/{item_id}") # @with query parameters def read_item(item_id: int, q: str = None): Return
'{
'	"item_id": item_id, "q": q
'}
#Create a PDF from a HTML string using Python
	#Export to a file or Stream
	#To view the file in the browser, use "inline" for the media_type
	#Create a FileResponse object with the file path, media type and headers
	#Return the FileResponse object
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@app.@get("/pdf") async def get_pdf(greet1: str = None,greet2: str = None): renderer = ChromePdfRenderer() content = "<h1>Document Generated using IronPDF with fastapi GET</h1>" content += "<p> Demonstrate PDF generation using User Inputs"+"</p>" content += "<p>"+f"Greetings from: {greet1}"+"</p>" content += "<p>"+f"And Greetings from: {greet2}"+"</p>" pdf = renderer.RenderHtmlAsPdf(content) pdf.SaveAs("fastapi.pdf") headers = { "Content-Disposition": "inline; filename=sample.pdf" } response = FileResponse("fastapi.pdf", media_type="application/pdf", headers=headers) Return response
VB   C#

程式碼說明

以下代碼片段展示了 IronPDF 與 FastAPI 的整合,根據用戶輸入動態生成 PDF 文件,並將其作為可下載的回應提供。

  1. 設定授權金鑰: 應用IronPDF授權金鑰以啟用其功能。

  2. FastAPI 初始化: 初始化一個 FastAPI 實例 (app) 處理 HTTP 請求。3. 基本路由處理器:`read_root()`:當訪問根 URL 時,以簡單的 JSON 訊息回應 "Hello IronPDF" (`/`). `read_item()`:接受 `item_id` 路徑參數和可選 `q` 查詢參數。 返回一個包含這些函數參數的 JSON 回應。

  3. PDF 生成路徑 (`/pdf`):`get_pdf()`:

    • 此异步函数处理对 `/pdf` 端点的 GET 请求,带有可选查询参数名 (greet1greet2).
    • 構建 HTML 字串 (內容) 包括:一個標題,指出文件的來源和目的。 使用用戶輸入演示 PDF 生成的段落 (greet1greet2). 使用 ChromePdfRenderer()從 IronPDF 將 HTML 內容渲染成 PDF (`pdf = renderer.RenderHtmlAsPdf(內容)).
    • 將生成的 PDF 保存為「fastapi.pdf」 (`pdf.SaveAs("fastapi.pdf")).5. 提供 PDF:
    • 配置響應標頭以指定 PDF 應在瀏覽器中內嵌顯示 (`"Content-Disposition": "inline; filename=sample.pdf"`).
    • 創建一個 FileResponse 對象來指向具有適當媒體類型的生成 PDF 文件 ("application/pdf").
    • 返回 FileResponse 物件,當訪問 /pdf 端點時觸發 PDF 文件的下載。

    以下程式碼片段說明了如何將IronPDF無縫整合到FastAPI中,以根據使用者輸入動態生成和提供PDF文件。 它展示了將 HTML 內容轉換為 PDF 的能力,使其適用於需要即時生成文件並通過 HTTP 傳送的應用程式。

輸出

以下顯示從 API 生成的 swagger 輸出

FastAPI Python(對開發者的運作方式):圖2

PDF

FastAPI Python(對開發人員的運作方式):圖 3

IronPDF 授權

IronPDF 運行於 Python 的授權金鑰上。 IronPDF for Python 提供 یک 免費試用 授權金鑰允許用戶在購買前檢查功能。

在使用IronPDF套件之前,將授權密鑰放在腳本的開頭:

from ironpdf import * 
# Apply your license key
License.LicenseKey = "key"
from ironpdf import * 
# Apply your license key
License.LicenseKey = "key"
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

結論

FastAPI 是一個強大且易於使用的框架,用於在 Python 中構建 API。 FastAPI 具有高效能、自動化文件和先進功能,使其成為初學者和經驗豐富的開發人員的理想選擇。 無論是構建簡單的 API 還是複雜的網路應用程式,FastAPI 都提供您成功所需的工具。

IronPDF 是一個強大的 Python 函式庫,用於從 HTML 內容創建、操作和呈現 PDF 文件。 它提供了將 HTML 轉換為 PDF、互動表單創建、PDF 操作等功能。 (合併,拆分),和文字提取。 非常適合輕鬆生成動態 PDF 並集成到各種 Python 應用程式中。

下一個 >
IronPDF For Python 與 PDFium Python 的比較

準備開始了嗎? 版本: 2024.9 剛剛發布

免費 pip 安裝 查看許可證 >