fastapi对视频播放加速方法

from fastapi import FastAPI, Request, HTTPException, Query

from fastapi.responses import StreamingResponse

import os

import aiofiles

app = FastAPI()

@app.get("/video")

async def stream_video(request: Request, name: str = Query(..., description="Name of the video file")):

file_path = f"videos/{name}"

if not os.path.isfile(file_path):

raise HTTPException(status_code=404, detail="Video not found")

file_size = os.path.getsize(file_path)

range_header = request.headers.get('Range')

start, end = parse_range_header(range_header, file_size)

async def iterfile(file_path, start: int, end: int):

async with aiofiles.open(file_path, mode='rb') as file:

await file.seek(start)

yield await file.read(end - start + 1)

headers = {

'Content-Range': f'bytes {start}-{end}/{file_size}',

'Accept-Ranges': 'bytes',

'Content-Length': str(end - start + 1),

'Content-Type': 'video/mp4',

}

return StreamingResponse(iterfile(file_path, start, end), headers=headers, status_code=206)

def parse_range_header(range_header: str, file_size: int):

if range_header is None:

return 0, file_size - 1

ranges = range_header.strip().split("=")[-1]

start, end = ranges.split("-")

start = int(start) if start else 0

end = int(end) if end else file_size - 1

if start >= file_size or end >= file_size or start > end:

raise HTTPException(status_code=416, detail="Requested Range Not Satisfiable")

return start, end

if name == "main":

import uvicorn

uvicorn.run(app, host="0.0.0.0", port=8000)

相关推荐
江公望13 小时前
Qt的环境变量QT_QPA_PLATFORM浅解
linux·qt
Wang's Blog14 小时前
Linux小课堂: 文件操作核心命令深度解析(cat、less、head、tail、touch 与 mkdir 命令)
linux·chrome·less
fruge16 小时前
Ubuntu服务器已下载Nginx安装包的安装指南
服务器·nginx·ubuntu
Do_GH16 小时前
【Linux】07.Ubuntu开发环境部署
linux·运维·ubuntu
勤源科技16 小时前
全链路智能运维中的实时流处理架构与状态管理技术
运维·架构
CHH321316 小时前
在 Mac/linux 的 VSCode 中使用Remote-SSH远程连接 Windows
linux·windows·vscode·macos
tryCbest17 小时前
Linux使用Docker部署项目后期更新
linux·运维·docker
孤独得猿17 小时前
聊天室项目开发——etcd的安装和使用
linux·服务器·c++·etcd
siriuuus17 小时前
Linux Tomcat 简单使用及 Nginx 反向代理
linux·nginx·tomcat
呱呱巨基18 小时前
vim编辑器
linux·笔记·学习·编辑器·vim