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)

相关推荐
wanhengidc37 分钟前
私有云具体是指什么
服务器·网络·游戏·智能手机·云计算
A星空12340 分钟前
三、Kconfig介绍以及制作menuconfig界面
linux·运维·服务器
爱上妖精的尾巴1 小时前
8-10 WPS JSA 正则表达式:贪婪匹配
服务器·前端·javascript·正则表达式·wps·jsa
zylyehuo1 小时前
Windows & Linux 双系统资料整理
linux·夯实基础
安科士andxe1 小时前
实操指南|安科士1.25G CWDM SFP光模块选型、部署与运维全攻略
运维·数据库·5g
口袋物联2 小时前
模板方法模式在 C 语言中的应用(含 Linux 内核实例)
linux·c语言·模板方法模式
Elastic 中国社区官方博客3 小时前
易捷问数(NewmindExAI)平台解决 ES 升级后 AI 助手与 Attack Discovery 不正常问题
大数据·运维·数据库·人工智能·elasticsearch·搜索引擎·ai
一个人旅程~3 小时前
Linux Fcitx5输入法这么难念的由来?
linux·经验分享·电脑·ai写作
开开心心就好3 小时前
一键加密隐藏视频,专属格式播放工具
java·linux·开发语言·网络·人工智能·macos
末日汐4 小时前
TCP编程简单回显服务
服务器·网络·tcp/ip