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)

相关推荐
小小哭包13 小时前
Nginx配置文件nginx.conf中文详解
运维·nginx
weixin_4316972013 小时前
onlyoffice预览nginx代理的静态文件
运维·nginx
杨云龙UP13 小时前
从0搭建Oracle ODA NFS异地备份:从YUM源到RMAN定时任务的全流程
linux·运维·数据库·oracle
DN金猿14 小时前
恢复 Linux 上误删除的文件
linux·运维·服务器
6***A66314 小时前
Nginx 反向代理配置
运维·nginx
远瞻。14 小时前
【环境配置】Ubuntu系统安装cuda
linux·运维·ubuntu
kyle~15 小时前
Linux---<unistd.h>类Unix系统编程核心头文件
linux·运维·unix
bendan5015 小时前
服务通过docker部署后,调用确定相互调用的URL
运维·docker·容器
闲人编程15 小时前
OpenAPI/Swagger规范与API文档自动化
运维·自动化·json·swagger·schema·openapi·codecapsule
python百炼成钢15 小时前
55.Linux ADC框架(IIO续)
linux·运维·服务器·驱动开发