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)

相关推荐
java龙王*11 分钟前
开放端口,开通数据库连接权限,无法连接远程数据库 解决方案
linux
bcbobo21cn1 小时前
Linux命令的命令历史
linux·histsize·histfile
jingyu飞鸟2 小时前
linux系统源代码安装apache、编译隐藏版本号
linux·运维·apache
世事如云有卷舒2 小时前
Ubunt20.04搭建GitLab服务器,并借助cpolar实现公网访问
linux·服务器·gitlab
Little-Hu2 小时前
QML TextEdit组件
java·服务器·数据库
riverz12273 小时前
TCP backlog工作机制
服务器·网络·tcp/ip
2401_858286113 小时前
OS15.【Linux】gdb调试器的简单使用
linux·运维·服务器·开发语言·gdb
c30%004 小时前
内网渗透——红日靶场五
运维·服务器
zjw_rp5 小时前
centos停止维护后更换yum源
linux·运维·centos
宇钶宇夕5 小时前
EPLAN 电气制图:建立自己的部件库,添加部件-加SQL Server安装教程(三)上
运维·服务器·数据库·程序人生·自动化