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)

相关推荐
DianSan_ERP4 小时前
如何通过抖店订单接口实现订单状态管理与履约自动化?
运维·自动化
b***25114 小时前
18650电池点焊机:电阻焊技术如何决定电池组的成败|深圳比斯特自动化
运维·自动化
原来是猿4 小时前
网络计算器:理解序列化与反序列化(中)
linux·运维·服务器·网络·tcp/ip
前端老曹5 小时前
Docker 从入门到放弃:完整指南
运维·docker·容器
AOwhisky5 小时前
虚拟化技术学习笔记
linux·运维·笔记·学习·虚拟化技术
rabbit_pro6 小时前
Docker compose部署Ollama使用模型
linux·运维·docker
笑洋仟8 小时前
docker的overlay2目录占用磁盘空间很大,清理办法
运维·docker·容器
m0_738120728 小时前
ctfshow靶场SSRF部分——基础绕过到协议攻击解题思路与技巧(一)
服务器·前端·网络·安全·php
木雷坞8 小时前
2026 年 5 月国内可用 Docker 镜像源列表与配置方法
运维·docker·容器