> 文章列表 > 【python】fastapi response返回文本、音视频多媒体资源实现

【python】fastapi response返回文本、音视频多媒体资源实现

【python】fastapi response返回文本、音视频多媒体资源实现

返回HTML

HTMLResponse是FastAPI中自带的一个响应类,用于返回HTML格式的响应。使用方法如下:

from fastapi import FastAPI, HTMLResponseapp = FastAPI()@app.get("/", response_class=HTMLResponse)
async def read_root():html_content = """<!DOCTYPE html><html><head><title>FastAPI HTMLResponse Example</title></head><body><h1>Hello, World!</h1></body></html>"""return html_content

在上面的例子中,我们在装饰器中指定了response_class=HTMLResponse,表示我们需要返回一个HTML响应。然后在函数中,我们返回了一个HTML格式的字符串。FastAPI会自动将这个字符串封装成一个HTMLResponse对象,并设置 Content-Typetext/html,将其返回给客户端。

返回图片

返回图片,可以使用FileResponse类。FileResponse类是FastAPI提供的专门用于返回文件的Response类。可以使用FileResponse类将图片文件作为响应返回给客户端。

示例代码:

from fastapi import FastAPI
from fastapi.responses import FileResponseapp = FastAPI()@app.get("/image")
async def get_image():filename = "path/to/image.jpg"return FileResponse(filename, media_type="image/jpeg")

在这个例子中,我们使用FileResponse类返回了一张图片。FileResponse类的第一个参数是文件的路径,第二个参数(media_type)是文件的MIME类型。在这个例子中,我们指定了图片的MIME类型为image/jpeg

返回音频

返回音频时,需要设置正确的media_type,通常为audio/mpegaudio/wav,具体取决于音频文件的格式。可以通过FileResponsemedia_type参数来设置,例如:

from fastapi import FastAPI
from fastapi.responses import FileResponseapp = FastAPI()@app.get("/audio")
async def get_audio():return FileResponse("audio.mp3", media_type="audio/mpeg")

在上述代码中,我们返回了名为audio.mp3的音频文件,并且将media_type设置为audio/mpeg

返回视频

视频通常返回的是视频文件的二进制数据,需要设置media_type为视频格式的MIME类型。以下是返回视频文件的示例代码:

from fastapi import FastAPI, Response
from fastapi.responses import FileResponseapp = FastAPI()@app.get("/video")
def read_video():video_path = "path/to/video.mp4"return FileResponse(video_path, media_type="video/mp4")

其中,FileResponse会使用media_type参数来设置响应的MIME类型。在这个例子中,我们将media_type设置为video/mp4,表示返回的是一个MP4格式的视频文件。

返回PDF

使用 media_type='application/pdf' 来返回 PDF 文件。下面是一个示例代码:

from fastapi import FastAPI
from fastapi.responses import FileResponseapp = FastAPI()@app.get("/download-pdf")
async def download_pdf():file_path = "/path/to/pdf/file.pdf"return FileResponse(file_path, media_type='application/pdf', filename="file.pdf")

其中,/path/to/pdf/file.pdf 是 PDF 文件在本地的路径,filename="file.pdf" 是下载下来的文件的名称。

总结

media 解释
HTMLResponse 返回HTML
image/jpeg 返回图片
audio/mpeg 返回音频
video/mp4 返回视频
application/pdf 返回PDF