如何使用 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中文网其他相关文章!

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,可以显着提升系统性能和可扩展性。

pythonarraysarecreatedusiseThearrayModule,notbuilt-Inlikelists.1)importThearrayModule.2)指定tefifythetypecode,例如,'i'forineizewithvalues.arreaysofferbettermemoremorefferbettermemoryfforhomogeNogeNogeNogeNogeNogeNogeNATATABUTESFELLESSFRESSIFERSTEMIFICETISTHANANLISTS。

除了shebang线,还有多种方法可以指定Python解释器:1.直接使用命令行中的python命令;2.使用批处理文件或shell脚本;3.使用构建工具如Make或CMake;4.使用任务运行器如Invoke。每个方法都有其优缺点,选择适合项目需求的方法很重要。

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

SublimeText3 Linux新版
SublimeText3 Linux最新版

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Dreamweaver Mac版
视觉化网页开发工具