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)

相关推荐
fanxiaohui121383 分钟前
元脑服务器的创新应用:浪潮信息引领AI计算新时代
运维·服务器·人工智能
若云止水43 分钟前
Ubuntu 下 nginx-1.24.0 源码分析 - cycle->modules[i]->ctx
linux·nginx·ubuntu
亦世凡华、1 小时前
快速部署:在虚拟机上安装 CentOS 7 的详细步骤
linux·运维·经验分享·centos·安装教程
Elastic 中国社区官方博客1 小时前
使用 Elastic-Agent 或 Beats 将 Journald 中的 syslog 和 auth 日志导入 Elastic Stack
大数据·linux·服务器·elasticsearch·搜索引擎·信息可视化·debian
星图辛某人1 小时前
《Linux命令行和shell脚本编程大全》第四章阅读笔记
linux·运维·笔记
gallonyin2 小时前
免root运行python保活守护进程supervisor
linux·开发语言·python
Charary3 小时前
字符设备驱动开发与杂项开发
linux·驱动开发
梦游钓鱼4 小时前
在window终端创建docker容器的问题
运维·docker·容器