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)

相关推荐
袁袁袁袁满2 小时前
Linux云服务器如何判断系统是否发生过异常断电?
linux·运维·服务器
一只鹿鹿鹿2 小时前
智慧水利一体化建设方案
大数据·运维·开发语言·数据库·物联网
学不完的2 小时前
haproxy
linux·运维·https·负载均衡·haproxy
LCG元3 小时前
STM32MP1边缘网关:Linux系统下Modbus转MQTT协议转换实战
linux·stm32·嵌入式硬件
cyber_两只龙宝4 小时前
Nginx--企业高性能web服务器高级配置详解
linux·运维·nginx·云原生
如若1235 小时前
AutoDL云服务器 NVIDIA 570驱动 EGL渲染修复全记录
运维·服务器·python
i建模5 小时前
Omarchy设置防火墙
linux·运维
晚秋大魔王6 小时前
泰拉瑞亚手机版服务器部署
运维·服务器·泰拉瑞亚
敲代码的哈吉蜂6 小时前
高可用集群Keepalived
运维·服务器·网络·数据库
S-码农6 小时前
Linux ——条件变量
linux·开发语言