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)

相关推荐
冰封之寂6 小时前
Docker 资源管理终极指南:CPU、内存与 IO 的精细化控制
linux·运维·服务器·docker·云计算
xiaoye-duck7 小时前
《Linux系统编程》Linux 系统多线程(五):<线程同步与互斥>线程互斥(上):从条件变量到生产者消费者模型详解
linux·线程
小柯南敲键盘7 小时前
图片翻译API接入与自动化实现指南
运维·python·自动化
云计算磊哥@8 小时前
运维开发宝典058-大型网站nginx服务器管理全集4
服务器·nginx·运维开发
952368 小时前
Docker - 基础
运维·后端·docker·容器
Promise微笑8 小时前
智能激光清障仪选型指南:高效运维与安全保障的关键考量
运维·安全
Code_Ignis8 小时前
docker国内可用源(持续维护)
运维·docker·容器
一叶龙洲8 小时前
向日葵远程Ubuntu,支持隐私屏
linux·运维·ubuntu
酷可达拉斯9 小时前
Linux操作系统-shell编程之Grep与正则表达式
linux·运维·服务器·正则表达式·centos
寒水馨9 小时前
Linux下载、安装llama.cpp-b10068(附安装包llama-b10068-bin-ubuntu-vulkan-x64.tar.gz)
linux·ubuntu·llm·llama·本地部署·llama.cpp·推理引擎