如何解決透過POST 要求傳送JSON 資料時FastAPI 的422 錯誤
422 無法處理實體錯誤通常發生在要求的負載上時正確,但與伺服器的期望不符。在這種特定情況下,您遇到此錯誤是因為您的要求正在嘗試將 JSON 資料傳送到預期接收資料作為查詢參數的端點。
要解決此問題,有多種方法 可用:
選項1:利用Pydantic模型
- Pydantic 模型可讓您指定端點的預期資料結構。下面的程式碼片段說明如何定義接受表示為Pydantic 模型的JSON 資料的端點:
from pydantic import BaseModel class User(BaseModel): user: str @app.post('/') def main(user: User): return user
選項2:使用主體參數
- 如果不需要Pydantic 模型,您可以利用Body 參數。 'Body' 參數embed 允許您將請求正文作為函數簽名的一部分嵌入:
from fastapi import Body @app.post('/') def main(user: str = Body(..., embed=True)): return {'user': user}
選項3:使用字典類型
- 另一種方法(雖然不太推薦)是使用Dict 類型來定義鍵值對。但是,此技術不支援自訂驗證:
from typing import Dict, Any @app.post('/') def main(payload: Dict[Any, Any]): return payload
選項4:直接存取請求正文
- Starlette 的Request 物件允許直接存取使用await request.json() 存取已解析的JSON 請求正文。但是,此方法不提供自訂驗證,並且需要對端點定義使用 async def:
from fastapi import Request @app.post('/') async def main(request: Request): return await request.json()
測試選項
使用Python「請求」函式庫:
import requests url = 'http://127.0.0.1:8000/' payload = {'user': 'foo'} resp = requests.post(url=url, json=payload) print(resp.json())
使用JavaScript 的Fetch API:
fetch('/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({'user': 'foo'}) }).then(resp => resp.json()) .then(data => { console.log(data); }) .catch(error => { console.error(error); });透過選擇並實作其中一種方法,您可以成功處理JSON 資料您的FastAPI 端點,解決了422 錯誤。
以上是如何修復 FastAPI 在 POSTing JSON 資料時出現的 422 錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

forloopsareadvantageousforknowniterations and sequests,供應模擬性和可讀性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver Mac版
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。