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)

相关推荐
赵文宇(温玉)2 小时前
Docker离线安装
运维·docker·容器
进击的荆棘2 小时前
Linux网络——传输层协议UDP
linux·运维·服务器·网络·udp
Android系统攻城狮3 小时前
FFmpeg深度解析之av_bsf_get_by_name:如何查找码流过滤器?(七十九)
linux·运维·ffmpeg·音视频进阶·ffmpeg音视频
Decay__4 小时前
PostgreSQL 监控体系构建 —— postgres_exporter + Prometheus + Grafana 全栈实战
运维·数据库·sql·postgresql
ShineWinsu5 小时前
对于Qt:TCP的解析
linux·c++·qt·网络协议·面试·tcp·客户端
Decay__6 小时前
PostgreSQL 告警与自动化运维 —— 告警分级收敛、Webhook、定时巡检、脚本库
运维·数据库·sql·postgresql
笔记本note6 小时前
Linux GPIO 技术详解
linux·gpio
东坡大表哥7 小时前
【Ubuntu】Ubuntu 20.04 LTS → 22.04 LTS 升级实录
android·linux·ubuntu
程序员agions7 小时前
Docker Compose 生产环境配置记录
运维·docker·容器
郝学胜-神的一滴7 小时前
Effective Python 条款45:巧用属性注解平滑升级类属性
运维·开发语言·数据库·python·网络协议·numpy