python视频播放接口
import os
import uuid
from flask import Flask, Response, request
from flask_limiter import Limiter
app = Flask(__name__)
limiter = Limiter(app) # 初始化限流扩展
current_dir = os.path.dirname(os.path.abspath(__file__))
video_files = {
'video1': os.path.join(current_dir, 'videos', '1.mp4'),
'video2': os.path.join(current_dir, 'videos', '2.mp4'),
'video3': os.path.join(current_dir, 'videos', '3.mp4'),
'video4': os.path.join(current_dir, 'videos', '4.mp4'),
'video5': os.path.join(current_dir, 'videos', '5.mp4'),
'video6': os.path.join(current_dir, 'videos', '6.mp4')
}
temp_dir = 'Temp'
os.makedirs(temp_dir, exist_ok=True)
# 加载视频文件到内存
loaded_videos = {}
for video_id, video_path in video_files.items():
with open(video_path, 'rb') as f:
video_bytes = f.read()
loaded_videos[video_id] = video_bytes
@app.route('/play_video/', methods=['GET'])
# @limiter.limit("2 per minute") # 设置限流规则
@limiter.limit("5 per second") # 设置限流规则为最多同时 5 个请求
def play_video(video_id):
if video_id not in loaded_videos:
return "Video not found", 404
video_bytes = loaded_videos[video_id]
return Response(video_bytes, content_type='video/mp4')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5789)