使用 FastAPI 傳回 JSON 格式的資料
開發 FastAPI 應用程式時,了解傳回 JSON 格式資料的細微差別至關重要。這需要深入研究 FastAPI 的內部工作原理並理解 JSON 序列化所扮演的角色。
JSON 序列化的困境
問題的核心在於 json.dumps() 的使用在返回物件之前序列化物件。雖然這種方法看起來合乎邏輯,但它引入了冗餘序列化,因為 FastAPI 在回應產生期間自動對傳回值進行 JSON 編碼。這會導致 JSON 資料的字串表示看似不正確,而不是格式整齊的字典。
解決方案
要修正此問題,您必須允許 FastAPI 處理 JSON 序列化過程。這可以透過直接傳回資料物件(字典、列表等)來實現。 FastAPI 將使用 jsonable_encoder 將它們無縫轉換為 JSON 相容的數據,並將其包裝在 JSONResponse 中。產生的回應將包含 application/json 編碼數據,確保所需的 JSON 格式。
實作選項
選項1:使用回傳值
如預期回傳資料物件:
@app.get('/') async def main(): return d
在幕後,FastAPI 將使用JSONResponse 序列化dict (d)並使用json.dumps().
選項2:自訂回應物件
如果需要精確控制回應,請直接使用Response物件:
@app.get('/') async def main(): return Response(content=json.dumps(d, indent=4, default=str), media_type='application/json')
這種方法授予您對media_type 的自由(例如,「application/json」),提供可自訂性。
注意: json.dumps() (str) 的預設參數允許日期時間物件的序列化。透過傳遞縮進,您可以控制 JSON 輸出的格式。
以上是如何在FastAPI應用程式中高效返回JSON格式的資料?的詳細內容。更多資訊請關注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
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

記事本++7.3.1
好用且免費的程式碼編輯器

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

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