Sanic 实现 HTTP Range,解决前端视频无法拖动问题

python 复制代码
from sanic import Sanic, response
from sanic.response import json
from sanic.response.types import HTTPResponse, JSONResponse, ResponseStream
from mimetypes import guess_type
from sanic.compat import Header, open_async, stat_async
from sanic.response import file_stream
from urllib.parse import quote, unquote
import os


app = Sanic("private-web")

def parse_range_header(range_header, file_size):
    # 解析Range参数
    start, end = range_header.split('=')[1].split('-')
    start = int(start)
    end = int(end) if end else file_size - 1

    # 确保范围在文件大小范围内
    start = min(max(start, 0), file_size - 1)
    end = min(end, file_size - 1)

    return start, end

@app.route('/video/<vid:str>')
async def videoRange(request, vid):
    # 网址中文转码
    vid = unquote(vid)
    # 视频路径
    file_path = f"{vid}.mp4"
    # 获取文件大小
    file_size = os.path.getsize(file_path)
    # 获取请求头Range参数
    range_header = request.headers.get("Range")
    headers = {}

    if range_header:
        # 解析Range参数
        start, end = parse_range_header(range_header, file_size)
        status = 206
        headers["Content-Range"] = f"bytes {start}-{end}/{file_size}"
        headers['Content-Length'] = str(end - start + 1)
        chunk_size: int = 4096
        mime_type = None
        mime_type = mime_type or guess_type(file_path)[0] or "text/plain"
        # 这段代码就是拿 file_stream 里的源码改的,直接使用file_stream总是报错,有大佬帮忙解释并实现下吗
        async def _streaming_fn(response):
            async with await open_async(file_path, mode="rb") as f:
                await f.seek(start)
                to_send = end - start + 1
                while to_send > 0:
                    content = await f.read(min((to_send, chunk_size)))
                    if len(content) < 1:
                        break
                    to_send -= len(content)
                    await response.write(content)

        return ResponseStream(
            streaming_fn=_streaming_fn,
            status=status,
            headers=headers,
            content_type=mime_type,
        )
    else:
        return await file_stream(file_path, headers=headers)

if __name__ == '__main__':
    app.run(host='0.0.0.0')
相关推荐
二川bro1 小时前
模型部署实战:Python结合ONNX与TensorRT
开发语言·python
秋邱1 小时前
AI + 社区服务:智慧老年康养助手(轻量化落地方案)
人工智能·python·重构·ar·推荐算法·agi
rising start1 小时前
三、FastAPI :POST 请求、用户接口设计与 Requests 测试
python·网络协议·http·fastapi
CM莫问2 小时前
详解机器学习经典模型(原理及应用)——岭回归
人工智能·python·算法·机器学习·回归
SunnyRivers2 小时前
Python打包指南:编写你的pyproject.toml
python·打包·toml
计算机毕设小月哥2 小时前
【Hadoop+Spark+python毕设】中式早餐店订单数据分析与可视化系统、计算机毕业设计、包括数据爬取、数据分析、数据可视化
后端·python
n***26562 小时前
Python连接SQL SEVER数据库全流程
数据库·python·sql
β添砖java2 小时前
python第一阶段第六章python数据容器
开发语言·python
o***36932 小时前
python爬虫——爬取全年天气数据并做可视化分析
开发语言·爬虫·python
q***31143 小时前
【JAVA进阶篇教学】第十二篇:Java中ReentrantReadWriteLock锁讲解
java·数据库·python