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)

相关推荐
cccccc语言我来了2 分钟前
Linux (11) 进程控制
linux·运维·数据库
菜菜的院子8 分钟前
WSL2 运行 Ubuntu 26.04 完整 GNOME 桌面(WSLg Wayland)
linux·运维·ubuntu·wsl
暖核16 分钟前
从 CentOS 到 Ubuntu24.04 运维迁移手册:命令对照表 + 实操 + 避坑
linux·运维·centos
分布式存储与RustFS18 分钟前
训练集放在 RustFS 上,怎么像本地盘一样快?用 Curvine 加一层 POSIX 缓存
运维·云原生·开源·对象存储·分布式存储·s3·性能基准
pride.li19 分钟前
第12章 Python 教程-流程控制:循环结构
linux·服务器·python·算法
迷途之人不知返24 分钟前
【基础IO】-5-简单理解三个标准流——stdin、stdout、stderr
linux
牛马鸡niumasi25 分钟前
【Linux】进程退出
linux
北京中科新远科技26 分钟前
高速光链路故障排查实战:从DOM光功率到FEC与BER
运维·服务器·网络
秋名山小白1 小时前
UI自动化-Airtest框架落地实战
运维·ui·自动化
刘胡子大叔1 小时前
Docker 容器名 ping 不通
运维·docker·容器