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)

相关推荐
NaMM CHIN2 分钟前
linux redis简单操作
linux·运维·redis
猫头虎4 分钟前
楚存科技CSD32GAZIGY SD NAND贴片式TF卡深度评测:小身材大容量,嵌入式存储新选择
linux·服务器·网络·人工智能·windows·科技·芯片
IT布道6 分钟前
[GitLab] 项目源码迁移踩坑记
运维·gitlab
Strugglingler7 分钟前
Linux Device Drivers-第七章 时间, 延迟及延缓操作
linux·笔记
IMPYLH8 分钟前
Linux 的 sha512sum 命令
linux·运维·服务器·bash·哈希算法·散列表
维吉斯蔡12 分钟前
【Ubuntu】Fcitx 搜狗拼音无法在 VS Code 输入中文的修复方案
linux·vscode·ubuntu·bash
源远流长jerry13 分钟前
从 Nginx 到 DPVS:高性能负载均衡之路
linux·网络·tcp/ip·nginx·负载均衡
NEKGod19 分钟前
Linux 文件篡改审计(auditctl 实战指南)
linux·运维·chrome
计算机安禾23 分钟前
【Linux从入门到精通】第12篇:进程的前后台切换与信号控制
linux·运维·算法
Cyan_RA930 分钟前
如何利用 Paddle-OCR 丝滑进行复杂版面 PDF 的批量化OCR处理?
java·linux·python·ocr·conda·paddle·surya