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)

相关推荐
uiop_uiop_uiop3 小时前
fnOS LUKS on RAID Storage Pool
服务器
IT大白鼠3 小时前
Linux进程与计划任务管理:技术详解与实战指南
linux·运维·服务器
拾贰_C3 小时前
【Ubuntu | 公共工作站 | mysql 】 MySQL残留物残留数据
linux·mysql·ubuntu
临街的小孩3 小时前
Docker 容器内运行 ROS Noetic 图形界面(rqt_image_view)极简教程总结
运维·docker·容器
Ujimatsu4 小时前
虚拟机安装Ubuntu 26.04.x服务器版(命令行版)(2026.5)
linux·windows·ubuntu
hweiyu004 小时前
Linux命令:arptables
linux·运维
看到代码头都是大的5 小时前
Windows环境下绿色版nginx 1.30使用
运维·nginx
IT研究所5 小时前
AI 时代下的知识管理:从 Claude 的“复盘”能力看生成式 AI价值
大数据·运维·数据库·人工智能·科技·低代码·自然语言处理
仙柒4155 小时前
管理网络安全
linux·运维·服务器