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)

相关推荐
Championship.23.243 小时前
Linux 3.0 锁机制与故障排查详解
linux·运维·服务器
天疆说3 小时前
Zotero Connector 在 Edge 里找不到桌面 Zotero(Linux / Zotero 9.0.6 / Edge 150)
linux·前端·edge
风123456789~5 小时前
【Linux专栏】ls 排除某个文件
linux·运维·服务器
IT曙光6 小时前
ubuntu apt-get离线源制作
linux·ubuntu
其实防守也摸鱼6 小时前
运维--学习阶段问题解答(1)(自测)
linux·运维·服务器·数据库·学习·自动化·命令模式
懒鸟一枚6 小时前
深入理解 Linux 内存、Swap 交换分区与分页机制的关系
java·linux·数据库
玖玥拾7 小时前
C# 语言进阶(十五)C# 游戏服务端 MySQL 数据库
服务器·开发语言·网络·数据库·mysql·c#
土星云SaturnCloud7 小时前
边缘计算驱动绿氢生产过程智能寻优:电解槽级实时优化技术解析
服务器·人工智能·ai·边缘计算
Darkwanderor7 小时前
对Linux的进程控制的研究
linux·运维·c++
Web极客码8 小时前
突破并发瓶颈:云端高性能架构如何赋能海外 AI Agent 矩阵的高效产出
服务器·人工智能·架构