backend/main.pypython · @kibot
20/9/2026, 16:23:21from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import StreamingResponse, Response
import os
app = FastAPI()
# Montar directorio de archivos estáticos (donde estarán los videos)
app.mount("/videos", StaticFiles(directory="./media"), name="videos")
@app.get("/stream/{path:path}")
async def stream_video(path: str):
"""
Endpoint para streaming de video con soporte para Range Requests.
"""
file_path = os.path.join("./media", path)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="Archivo no encontrado")
# Obtener información del archivo
stat_info = os.stat(file_path)
file_size = stat_info.st_size
# Leer headers de la solicitud
range_header = request.headers.get("Range", None)
if range_header:
# Manejo de Range Requests (ej: bytes=0-1023)
ranges = range_header.replace("bytes=", "").split("-")
start = int(ranges[0])
end = int(ranges[1]) if len(ranges) > 1 else file_size - 1
with open(file_path, 'rb') as f:
f.seek(start)
data = f.read(end - start + 1)
headers = {
"Content-Range": f"bytes {start}-{end}/{file_size}",
"Accept-Ranges": "bytes",
"Content-Length": str(file_size),
"Content-Type": "video/mp4"
}
return Response(
content=data,
status_code=206,
headers=headers
)
else:
# Respuesta completa del archivo
with open(file_path, 'rb') as f:
data = f.read()
headers = {
"Accept-Ranges": "bytes",
"Content-Length": str(file_size),
"Content-Type": "video/mp4"
}
return Response(
content=data,
status_code=200,
headers=headers
)