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)

相关推荐
CCPC不拿奖不改名2 小时前
虚拟机基础:在VMware WorkStation上安装Linux为容器化部署打基础
linux·运维·服务器·人工智能·milvus·知识库搭建·容器化部署
山峰哥3 小时前
数据库调优实战:索引策略与查询优化案例解析
服务器·数据库·sql·性能优化·编辑器
fjh19973 小时前
记一次奇怪的ssh公钥登录失败的情况
运维·ssh
一只自律的鸡4 小时前
【Linux系统编程】文件IO 函数篇
linux·linux系统编程
dinga198510266 小时前
linux上redis升级
linux·运维·redis
hzc09876543216 小时前
Linux系统下安装配置 Nginx 超详细图文教程_linux安装nginx
linux·服务器·nginx
jjjxxxhhh1236 小时前
【加密】-AES与对称加密
java·服务器·网络
匀泪6 小时前
云原生(nginx实验(2))
运维·nginx·云原生
RisunJan7 小时前
Linux命令-ltrace(用来跟踪进程调用库函数的情况)
linux·运维·服务器
阿乐艾官7 小时前
【 LVM 创建逻辑卷】
linux