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)

相关推荐
wzyannn18 分钟前
Linux字符设备驱动开发详细教程(简单字符设备驱动框架)
linux·运维·驱动开发·嵌入式
LCG元34 分钟前
Linux 下的端口转发:ssh、socat、iptables 三种方案对比
linux
LCG元36 分钟前
深入理解 Linux 网络命名空间:自己动手实现"虚拟网络"
linux
馨谙1 小时前
RHEL 存储堆栈完全解析:从硬件到应用的存储管理指南
服务器·开发语言·php
powerfulhell1 小时前
11.11作业
linux·运维·centos
板鸭〈小号〉1 小时前
进程间关系(linux)
linux·运维·服务器
liu****1 小时前
18.HTTP协议(一)
linux·网络·网络协议·http·udp·1024程序员节
脏脏a2 小时前
【Linux】冯诺依曼体系结构与操作系统概述
linux·服务器
恪愚2 小时前
webRTC:流程和socket搭建信令服务器
运维·服务器·webrtc
wudl55662 小时前
Flink20 SQL 窗口函数概述
服务器·数据库·sql