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 小时前
【Linux】进度条:行缓冲区、\r 与 fflush 的实战
linux·服务器·开发语言·数据结构·后端
宋冠巡3 小时前
华为云开发桌面OpenEuler搭建Nginx服务器实操记录
服务器·nginx·华为云
say_fall3 小时前
Linux进程核心概念:命令行参数与环境变量深度解析
linux·运维·服务器·ubuntu
go不是csgo3 小时前
Go-GMP-调度器深度解析(改进版本)
java·linux·golang
Peace3 小时前
【Zabbix】
linux·运维·zabbix
枕星而眠3 小时前
C++面向对象核心:类间关系与继承深度解析
运维·开发语言·c++·后端
FBI HackerHarry浩3 小时前
在Python中TCP网络程序开发的步骤流程
运维·服务器·开发语言·网络·python·pycharm
qq_452396233 小时前
第十一篇:《Docker Compose:多容器应用编排入门》
运维·docker·容器
kTR2hD1qb3 小时前
Keepalived 学习总结
java·服务器·学习
Geoking.3 小时前
Docker安装Nacos指南
运维·docker·容器