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)

相关推荐
略略略咯咯3 小时前
jenkins
运维·servlet·jenkins
艾醒(AiXing-w)3 小时前
LangChain 1.0 入门(五):提示词工程、partial变量、ChatPromptTemplate、Hub模板库
服务器·网络·langchain
java_logo4 小时前
Docker 部署 TypeWords:轻松搭建英语单词与文章练习平台
运维·docker·容器·轩辕镜像·typewords·英语单词练习·四级单词练习
姚永强4 小时前
zabbix排查思路
运维·zabbix
wno7044 小时前
nginx反向代理设置ssl,支持https
运维·服务器·网络
weixin_403810134 小时前
安卓自动化脚本 HID 硬件选购指南:蓝牙HID与OTG HID区别、成本与搭建教程
android·运维·自动化·hid·安卓自动化脚本·安卓中控
盐焗鹌鹑蛋4 小时前
【Linux】消息队列和信号量
linux
circuitsosk4 小时前
Python 文件读写与上下文管理器:with 语句为什么是最佳选择
java·服务器·python·文件操作·上下文管理器·contextlib
Shawn Dev4 小时前
没有公网 IP,如何让家里的服务器通过域名访问?——Cloudflare Tunnel 实战指南
服务器·网络协议·tcp/ip
智者向内寻求力量4 小时前
【记录】ubuntu 24.04 安装在levnoval PC上之后,蓝牙设备找不到解决方法
linux·服务器·ubuntu