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)

相关推荐
信创天地12 分钟前
国产堡垒机部署实战:以奇安信、天融信为例构建运维安全三重防线
运维·安全
呉師傅1 小时前
东芝3525AC彩色复印机CC219测试页打印方法【实际操作】
运维·网络·windows·计算机外设·电脑
凯子坚持 c2 小时前
Protocol Buffers C++ 进阶数据类型与应用逻辑深度解析
java·服务器·c++
宴之敖者、2 小时前
Linux——权限
linux·运维·服务器
刘叨叨趣味运维2 小时前
Linux性能排查实战:从“系统慢”到精准定位
linux
txinyu的博客2 小时前
MAC 地址
服务器·网络·macos
oscar9993 小时前
构建敏捷团队的DevOps测试策略:速度与可靠性的平衡艺术
运维·测试·devops
欣然~3 小时前
法律案例 PDF 批量转 TXT 工具代码
linux·前端·python
星辰&与海4 小时前
Proxmox导入虚拟机后进入dracut紧急模式
运维
阮松云4 小时前
a start job is running for Builds and install new kernel modules through DKMS
linux·centos