返回HTML
HTMLResponse
是FastAPI中自帶的一個響應類,用于返回HTML格式的響應。使用方法如下:
from fastapi import FastAPI, HTMLResponse
app = 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響應。然后在函數(shù)中,我們返回了一個HTML格式的字符串。FastAPI會自動將這個字符串封裝成一個HTMLResponse
對象,并設(shè)置 Content-Type
為 text/html
,將其返回給客戶端。
返回圖片
返回圖片,可以使用FileResponse
類。FileResponse
類是FastAPI提供的專門用于返回文件的Response類??梢允褂?code>FileResponse類將圖片文件作為響應返回給客戶端。
示例代碼:
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get("/image")
async def get_image():
filename = "path/to/image.jpg"
return FileResponse(filename, media_type="image/jpeg")
在這個例子中,我們使用FileResponse
類返回了一張圖片。FileResponse
類的第一個參數(shù)是文件的路徑,第二個參數(shù)(media_type
)是文件的MIME類型。在這個例子中,我們指定了圖片的MIME類型為image/jpeg
。
返回音頻
返回音頻時,需要設(shè)置正確的media_type
,通常為audio/mpeg
或audio/wav
,具體取決于音頻文件的格式??梢酝ㄟ^FileResponse
的media_type
參數(shù)來設(shè)置,例如:
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get("/audio")
async def get_audio():
return FileResponse("audio.mp3", media_type="audio/mpeg")
在上述代碼中,我們返回了名為audio.mp3
的音頻文件,并且將media_type
設(shè)置為audio/mpeg
。
返回視頻
視頻通常返回的是視頻文件的二進制數(shù)據(jù),需要設(shè)置media_type
為視頻格式的MIME類型。以下是返回視頻文件的示例代碼:
from fastapi import FastAPI, Response
from fastapi.responses import FileResponse
app = FastAPI()
@app.get("/video")
def read_video():
video_path = "path/to/video.mp4"
return FileResponse(video_path, media_type="video/mp4")
其中,FileResponse
會使用media_type
參數(shù)來設(shè)置響應的MIME類型。在這個例子中,我們將media_type
設(shè)置為video/mp4
,表示返回的是一個MP4格式的視頻文件。
返回PDF
使用 media_type='application/pdf'
來返回 PDF 文件。下面是一個示例代碼:文章來源:http://www.zghlxwxcb.cn/news/detail-426857.html
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = 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"
是下載下來的文件的名稱。文章來源地址http://www.zghlxwxcb.cn/news/detail-426857.html
總結(jié)
media | 解釋 |
---|---|
HTMLResponse | 返回HTML |
image/jpeg | 返回圖片 |
audio/mpeg | 返回音頻 |
video/mp4 | 返回視頻 |
application/pdf | 返回PDF |
到了這里,關(guān)于【python】fastapi response返回文本、音視頻多媒體資源實現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!