Flask结合Redis消息队列实现电影弹幕
用到的弹幕播放器插件:dplayer.js(开源)
1.安装Redis 2.安装flask-redis包 pip install flask-redis
3.下载dplayer
页面搭建
1.引入资源
<link rel="stylesheet" href="{{ url_for('static',filename='dplayer/dist/ DPlayer.min.css') }}"> <script src="{{ url_for('static',filename='dplayer/plugin/flv.min.js') }}"></script> <script src="{{ url_for('static',filename='dplayer/plugin/hls.min.js') }}"></script>
<script src="{{ url_for('static',filename='dplayer/dist/DPlayer.min.js') }}"></script>
2.添加样式
<!--样式--> <style> .dplayer-comment-setting-type>label{ display: inline;} </style>
3.播放器样式
<!--播放器 --> <div class="col-md-8"> <div id="dplayer1" style="height:500px;width: 774px;"></div>
</div>
4.弹幕js
<!--弹幕js--> <script> var dp1 = new DPlayer({ element: document.getElementById('dplayer1'), video: { url: "播放地址(电影文件地址)(例:{{ url_for('static',filename='uploads/'+movie.url) }})",
},danmaku: {
id: '电影ID'(例:{{movie.id}}),
api: "API地址(例:/tm/)"
}
});
</script>
<!--右侧添加滚动条--> <div class="panel-body" style="height:459px;overflow:scroll;">
视图处理等
1.在__init__.py中
<!--使 用 方法--> from flask.ext.redis import FlaskRedis app.config["REDIS_URL"] = "redis://localhost:6379/0" rd = FlaskRedis(app)
2.在视图层
API地址视图处理
#视图处理 @home.route("/tm/", methods=["GET", "POST"]) def tm(): import json from app import rd if request.method == "GET": id = request.args.get('id') key = "movie" + str(id) if rd.llen(key): msgs = rd.lrange(key, 0, 2999) res = { "code": 1, "danmaku": [json.loads(v) for v in msgs] } else: res = { "code": 1, "danmaku": [] } resp = json.dumps(res) if request.method == "POST": data = json.loads(request.get_data()) msg = { "__v": 0, "author": data["author"], "time": data["time"], "text": data["text"], "color": data["color"], "type": data['type'], "ip": request.remote_addr, "_id": datetime.datetime.now().strftime("%Y%m%d%H%M%S") + uuid.uuid4().hex, "player": [ data["player"] ] } res = { "code": 1, "data": msg } resp = json.dumps(res) rd.lpush("movie" + str(data["player"]), json.dumps(msg)) from flask import Response return Response(resp, mimetype='application/json')