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)

相关推荐
晚风吹北巷41 分钟前
Linux复习篇(自用)
linux·运维·服务器·1024程序员节
风哥2号1 小时前
数据库教程FGMT69:PostgreSQL运维诊断与监控分析
运维·数据库·postgresql
数字新视界1 小时前
信创机房动环监控技术在智能运维中的应用与优势分析
大数据·服务器·数据库·动环监控系统·动力与环境监控系统
by209991 小时前
Linux 压缩传输、进程查看与权限管理
linux·经验分享·1024程序员节
Harrison Ben2 小时前
(原创)SAP FI自动入账奥义:FBKP FBKA FBKF
运维·sap·sap fico·sap运维·sap 实施
无足鸟ICT2 小时前
【RHCA+】reboot命令(重启)
linux·运维·服务器·1024程序员节
DYWorker0013 小时前
第1课:基于正点原子RK3568开发板读懂Linux内核
linux·运维·网络
GlobalInfo3 小时前
全球及中国机器人现场部署服务行业研究报告(2026版):市场现状、行业前景与占有率分析
大数据·运维·人工智能
Android系统攻城狮3 小时前
Linux FFmpeg深度解析之avformat_open_input调用流程与实战(一)
linux·运维·ffmpeg·车载音视频·ffmpeg音视频·音视频进阶手册
分布式存储与RustFS3 小时前
把 LSM 引擎直接架在对象存储上:slatedb 能不能跑在 RustFS 上?
运维·云原生·开源·对象存储·分布式存储·s3·性能基准