如何使用FastAPI 發布資料後下載檔案
問題
您正在建立一個處理文字輸入的Web 應用程序,將其轉換為語音,並返回音訊檔案以供下載。您需要在 HTML 頁面上提供下載選項,但無法正確實現它。
在 Flask 中,可以使用 send_file 函數實作類似的設定。如何使用 FastAPI 複製此功能?
FastAPI 程式碼和 HTML 範例
<code class="python">from fastapi import FastAPI, File, Form, UploadFile from fastapi.responses import FileResponse, HTMLResponse from fastapi.templating import Jinja2Templates from gtts import gTTS templates = Jinja2Templates(directory="templates") def text_to_speech(language: str, text: str) -> str: tts = gTTS(text=text, lang=language, slow=False) tts.save("./temp/welcome.mp3") return "Text to speech conversion successful" @app.get("/") def home(request: Request): return templates.TemplateResponse("index.html", {"request": request}) @app.post("/text2speech") async def home(request: Request): if request.method == "POST": form = await request.form() if form["message"] and form["language"]: language = form["language"] text = form["message"] translate = text_to_speech(language, text) path = "./temp/welcome.mp3" value = FileResponse("./temp/welcome.mp3", media_type="audio/mp3") return value</code>
<code class="html"> <title>Download MP3 File</title> <h2 id="Download-a-file">Download a file</h2> <p><a href="%7B%7B%20url_for('text2speech')%20%7D%7D">Download</a></p></code>
解決方案
選項 1: 使用表單關鍵字確保所需參數。使用 Form(...) 使參數成為強制參數,而不是使用 wait request.form() 並手動檢查所需參數。處理接收到的資料後,使用 FileResponse 傳回文件,將 Content-Disposition 標頭設定為「附件」。
選項 2: 您也可以使用@app.api_route("/text2speech",methods=["GET", “郵政”])。或者,您可以使用 @app.get("/text2speech") 和 @app.post("/text2speech") 定義單獨的端點。
此外,您可以選擇使用 Fetch API 設定 JavaScript 介面來在前端下載檔案。
注意:
- 如果要傳回一個無法放入記憶體的大文件,請使用 StreamingResponse 分塊處理該文件。
- 要在下載後刪除文件,請建立一個要在回傳回應後執行的後台任務。
以上是如何在 FastAPI 中發布資料後下載檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

ArraySareAryallyMoremory-Moremory-forigationDataDatueTotheIrfixed-SizenatureAntatureAntatureAndirectMemoryAccess.1)arraysStorelelementsInAcontiguxufulock,ReducingOveringOverheadHeadefromenterSormetormetAdata.2)列表,通常

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Python列表可以存儲不同類型的數據。示例列表包含整數、字符串、浮點數、布爾值、嵌套列表和字典。列表的靈活性在數據處理和原型設計中很有價值,但需謹慎使用以確保代碼的可讀性和可維護性。

Pythondoesnothavebuilt-inarrays;usethearraymoduleformemory-efficienthomogeneousdatastorage,whilelistsareversatileformixeddatatypes.Arraysareefficientforlargedatasetsofthesametype,whereaslistsofferflexibilityandareeasiertouseformixedorsmallerdatasets.

theSostCommonlyusedModuleForCreatingArraysInpyThonisnumpy.1)NumpyProvidEseffitedToolsForarrayOperations,Idealfornumericaldata.2)arraysCanbeCreatedDusingsnp.Array()for1dand2Structures.3)

toAppendElementStoApythonList,usetheappend()方法forsingleements,Extend()formultiplelements,andinsert()forspecificpositions.1)useeAppend()foraddingoneOnelementAttheend.2)useextendTheEnd.2)useextendexendExendEnd(

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

金融、科研、医疗和AI等领域中,高效存储和处理数值数据至关重要。1)在金融中,使用内存映射文件和NumPy库可显著提升数据处理速度。2)科研领域,HDF5文件优化数据存储和检索。3)医疗中,数据库优化技术如索引和分区提高数据查询性能。4)AI中,数据分片和分布式训练加速模型训练。通过选择适当的工具和技术,并权衡存储与处理速度之间的trade-off,可以显著提升系统性能和可扩展性。


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

SublimeText3漢化版
中文版,非常好用

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

禪工作室 13.0.1
強大的PHP整合開發環境

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

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