Python Fastapi返回文件
在Web开发中,有时候我们需要返回文件给用户,比如下载一份PDF文件或者图片等。在Python中,使用Fastapi框架可以很方便地实现这个功能。本文将详细介绍如何使用Fastapi框架返回文件。
安装Fastapi
在开始之前,我们需要先安装Fastapi和uvicorn。可以使用pip命令来安装:
pip install fastapi uvicorn
返回普通文本文件
首先,我们来看如何返回一个普通的文本文件。我们可以将文本内容保存在一个变量中,并使用Response
类来返回该文本。
from fastapi import FastAPI, Response
app = FastAPI()
@app.get("/text_file")
def read_text_file():
text = "Welcome to geek-docs.com!"
return Response(content=text, media_type="text/plain")
上面的示例代码中,我们定义了一个路由/text_file
,当用户访问该路由时,会返回一个包含”Welcome to geek-docs.com!”的文本文件。
返回图片文件
除了文本文件,我们还可以返回图片文件。同样的方式,我们可以将图片内容保存在一个变量中,并使用Response
类返回该图片。
from fastapi import FastAPI, Response
from PIL import Image
import io
app = FastAPI()
@app.get("/image_file")
def read_image_file():
image = Image.new("RGB", (300, 300), "blue")
byte_io = io.BytesIO()
image.save(byte_io, "PNG")
return Response(content=byte_io.getvalue(), media_type="image/png")
上面的示例代码中,我们定义了一个路由/image_file
,当用户访问该路由时,会返回一个300×300的蓝色图片。
返回下载文件
有时候我们需要返回一个可供用户下载的文件,比如PDF文件。Fastapi也可以很方便地实现这个功能。我们可以使用FileResponse
类来返回一个文件。
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get("/download_pdf")
def download_pdf():
pdf_path = "path/to/your/pdf/file.pdf" # 文件路径
return FileResponse(pdf_path, media_type="application/pdf", filename="downloaded_file.pdf")
上面的示例代码中,我们定义了一个路由/download_pdf
,当用户访问该路由时,会返回一个PDF文件供用户下载。
总结
通过本文的介绍,我们学习了如何在Python中使用Fastapi框架返回文件。无论是普通的文本文件、图片文件还是可供用户下载的文件,Fastapi都提供了很好的支持,让我们能够轻松地实现这些功能。