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)

相关推荐
梁正雄18 小时前
6、prometheus资源规划
运维·服务器·服务发现·prometheus·监控
晨曦之旅19 小时前
零成本体验云计算!阿贝云免费服务器深度测评
运维·服务器·云计算
工具人555519 小时前
Linux 抓取 RAM Dump 完整指南
linux·运维·安全
会飞的小蛮猪19 小时前
SkyWalking运维之路(Java探针接入)
java·运维·经验分享·容器·skywalking
不懂音乐的欣赏者19 小时前
Windows 下 ROS/ROS2 开发环境最优解:WSL 比直接安装、虚拟机、双系统更优雅!
linux·windows·ubuntu·ros·wsl·ros2·双系统
天一生水water20 小时前
docker-compose安装
运维·docker·容器
神仙别闹20 小时前
基于C语言 HTTP 服务器客户端的实验
服务器·c语言·http
Archy_Wang_120 小时前
基于BaGet 构建NuGet私有库并实现类库打包到NuGet私有库
运维·jenkins
小狗爱吃黄桃罐头20 小时前
正点原子【第四期】Linux之驱动开发学习笔记-10.1 Linux 内核定时器实验
linux·驱动开发·学习
初听于你20 小时前
运维高级故障排除与恢复-SysRq
运维·服务器·安全