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 小时前
Ubuntu Linux系统配置账号无密码sudo
linux·服务器·ubuntu
爆农3 小时前
centos搭建dokcer和vulhub
linux·运维·centos
SZ1701102313 小时前
中继器的作用
服务器·网络·智能路由器
chenxy023 小时前
如何快速分享服务器上的文件
运维·服务器
重启就好4 小时前
【Ansible】模块详解
linux·服务器·ansible
o0o_-_4 小时前
【瞎折腾/mi50 32G/ubuntu】mi50显卡ubuntu运行大模型开坑(三)安装风扇并且控制转速
linux·运维·ubuntu
Huazzi.5 小时前
Ubuntu 22虚拟机【网络故障】快速解决指南
linux·网络·学习·ubuntu·bash·编程
熙曦Sakura5 小时前
【Linux网络】HTTP
linux·网络·http
轻颂呀5 小时前
Linux中常见开发工具简单介绍
linux
SuperW6 小时前
Linxu实验五——NFS服务器
运维·服务器