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)

相关推荐
程序员小崔日记4 小时前
20块钱注册一年 .COM 域名!Spaceship 最新优惠教程,支付宝即可付款(附优惠码)
服务器·腾讯云·域名
Better Bench4 小时前
WSL2 Ubuntu 中 Claude CLI “command not found” 故障排查与修复
linux·ubuntu·claude·wsl·claudecode
实心儿儿5 小时前
Linux —— 进程间关系和守护进程
linux·运维·服务器
FII工业富联科技服务5 小时前
工业设备运维如何Agentic化?拆解Factory Brain的设备运维架构
大数据·运维·人工智能·架构·制造
林浅不想努力5 小时前
LVS知识点总结
服务器·云原生·lvs
Dawn-bit6 小时前
Linux磁盘管理详解
linux·运维·服务器·计算机网络·云计算
RisunJan7 小时前
Linux命令-sftp(SSH 文件传输协议客户端)
linux·运维
极客先躯8 小时前
高级java每日一道面试题-2026年05月03日-实战篇[Docker]-如何实现容器化环境的数据加密?
java·运维·docker·容器·金融·加解密·高级面试
龙仔7259 小时前
人大金仓OS_Core数据库自动备份实施笔记(银河麒麟Linux)
linux·数据库·笔记·备份·人大金仓
老杨聊技术9 小时前
CentOS 7 安装 MySQL 8 保姆级教程
linux·mysql·centos