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)

相关推荐
zhangrelay11 分钟前
机器人或计算机智能与时间相关案例汇总(ROS2-ROS1)
linux·笔记·学习·ubuntu·机器人
沫璃染墨15 分钟前
《从零入门Linux系统篇(五十三):线程篇·六——线程互斥详解:从并发问题到mutex互斥锁》
linux·运维·服务器·开发语言·后端·架构·系统架构
程序员-Benothing17 分钟前
Shell循环教程:for、while、until、break、continue详解
linux·运维·服务器
旺仔Sec24 分钟前
2026年江西省职业院校技能大赛(高职组)麒麟工坊运维保障竞赛样题
运维
Zhang~Ling24 分钟前
Linux网络:五种IO模型及其工作原理与应用
linux·网络·php
雪落漂泊26 分钟前
Linux基本指令(下)
java·linux·服务器
小白的码BUG之路27 分钟前
Ubuntu -- 使用命令firewall-cmd
linux·运维·服务器
Chill6028 分钟前
非root用户怎么在ubuntu服务器上配置第三方的codex
linux·服务器·ubuntu
渡我白衣38 分钟前
深入理解 Transformer:Decoder与Masked_Attention
linux·服务器·网络·c++·人工智能·深度学习·transformer
赵民勇40 分钟前
gsettings命令详解
linux·运维