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)

相关推荐
@CLoudbays_Martin1113 分钟前
Linux 服务器如何查看是否被植入后门?
linux·服务器·网络·安全·github·ssl
拾光Ծ23 分钟前
【Linux网络】深入理解网络层:从IP协议格式,子网划分到NAT与路由机制
linux·网络·网络协议·tcp/ip·计算机网络
zho_uzhou33 分钟前
ubuntu服务端运行vue网页步骤
linux·服务器·vue.js·ubuntu
Archy_Wang_17 小时前
LVS+KeepAlived+Nginx实现企业级业务高可靠部署的实战教程
运维·nginx·lvs
张文君9 小时前
docker使用代理拉取镜像
运维·docker·容器
ltl9 小时前
纠删码原理与存储效率
linux
ltl10 小时前
MinIO 原理和架构:机制、AGPL 与上游 archived 风险
linux
陌路2010 小时前
Docker教程从入门到精通(0基础)
运维·docker·容器
林浩杨_10 小时前
linux搜索命令(grep+sed)
linux·命令模式
W.W.H.10 小时前
将驱动编译成模块并安装到rootfs
linux·物联网·wifi·rootfs·驱动