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)

相关推荐

  1. fastapi视频播放加速方法

    2024-06-18 20:40:01       33 阅读
  2. Vue实现视频播放

    2024-06-18 20:40:01       41 阅读
  3. vue前端播放视频

    2024-06-18 20:40:01       33 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-18 20:40:01       91 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-18 20:40:01       97 阅读
  3. 在Django里面运行非项目文件

    2024-06-18 20:40:01       78 阅读
  4. Python语言-面向对象

    2024-06-18 20:40:01       88 阅读

热门阅读

  1. 嵌入式就业前景好么

    2024-06-18 20:40:01       34 阅读
  2. 数据库回表及优化方法(附示例)

    2024-06-18 20:40:01       32 阅读
  3. 计算机网络模型面试题50题

    2024-06-18 20:40:01       32 阅读
  4. 图解ZGC

    图解ZGC

    2024-06-18 20:40:01      33 阅读
  5. [python日常]获取指定文件夹下,指定后缀的文件

    2024-06-18 20:40:01       29 阅读
  6. PostgreSQL源码分析——SeqScan

    2024-06-18 20:40:01       24 阅读
  7. css伪类和伪元素选择器

    2024-06-18 20:40:01       34 阅读
  8. 充电学习—2、开关电源基本原理

    2024-06-18 20:40:01       23 阅读