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)

相关推荐
Chirp35 分钟前
Windows下借助wsl2读取ext4格式磁盘
linux·windows
taocarts_bidfans42 分钟前
反向海淘站点运维优化与常见技术问题排查
大数据·运维·跨境电商·独立站·反向海淘
1892280486143 分钟前
NY386固态MT29F32T08GWLBHD6-T:B
大数据·服务器·人工智能·科技·缓存
IMPYLH43 分钟前
Linux 的 whoami 命令
linux·运维·服务器·bash
头歌实践平台43 分钟前
头歌静态路由与默认静态路由
运维·服务器·网络
NashSKY44 分钟前
RK3588 Linux SDK 编译、烧录与 MIPI 屏配置流程
linux·rk3588
宋浮檀s1 小时前
DVWA通关教程2
运维·服务器·前端·javascript
专注VB编程开发20年1 小时前
Python 的 C 扩展,本质上就是“去中心化的 COM”
java·服务器·开发语言·ide·python
JAVA社区1 小时前
Java进阶全套教程(七)—— Redis超详细实战详解
java·linux·开发语言·redis·面试·职场和发展
UrSpecial1 小时前
从零实现 Reactor + ThreadPool TCP 服务器
服务器·网络编程·reactor·tcp