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)

相关推荐
方便面不加香菜2 小时前
Docker Volume -- 对照总结及综合实战案例操作演示
运维·docker·容器
爱勇宝2 小时前
SSL 证书别再手动续了:acme.sh + Let's Encrypt + 云厂商 DNS 全自动实战
运维·服务器
数据库小学妹3 小时前
数据库容量规划:四个数与扩容触发线
运维·数据库·后端
dingdingfish4 小时前
TLPI 第52章 读书笔记:POSIX Message Queues
linux·mq·ipc·posix·message·tlpi
wacsii5 小时前
【Linux进程(五)】进程控制全解析:从创建、终止、等待到程序替换
linux·服务器
七夜zippoe5 小时前
Nexent Linux 部署:用 deploy.sh
linux·服务器·docker·部署·ai智能体·nexent
去码头整点薯条985 小时前
NFS服务器
linux·运维·服务器
蜗牛一步步往上爬6 小时前
第一章 初识Linux shell
linux·运维·服务器
拂拉氏6 小时前
【知识讲解】 Linux线程中锁的认识
linux·互斥锁