django中实时获取当前在线人数
2018-12-15 本文已影响165人
___大鱼___
settings.py
# 设置session过期时间
SESSION_COOKIE_AGE = 60 * 30 # 30分钟
views.py
def get_all_login_user():
SQL = """
SELECT * FROM `django_session` WHERE expire_date >= NOW() GROUP BY session_data;
"""
# 根据session值是否重复判断用户是否在线 不太完善
sessions = Session.objects.filter(expire_date__gte=datetime.now())
user_list = []
# 获取session中的用户id
for session in sessions:
data = session.get_decoded()
print(data)
user_list.append(data.get('_auth_user_id', None))
print(user_list, 66666666)
return user_list
user/views.py
@accept_websocket
def get_user_list(request):
if request.is_websocket():
message = request.websocket.wait()
while True:
if message:
user_list = BllUser().get_all_login_user()
request.websocket.send(str(len(user_list)))
time.sleep(10)
index.html
<div class="col-md-offset-1" style="display: inline-block;line-height: 48px;color:orange">
当前在线人数: <span id="online_number">0</span>
</div>
js
// 实时获取当前在线用户人数
var socket = new WebSocket("ws:" + window.location.host + "/user/get_user_list/");
socket.onopen = function () {
console.log('WebSocket open');//成功连接上Websocket
socket.send('adasdasda。。。。');//发送数据到服务端
};
socket.onmessage = function (e) {
$('#online_number').text(e.data)
};
socket.onclose=function(e){
console.log(e);
socket.close(); //关闭TCP连接
};
if (socket.readyState == WebSocket.OPEN) socket.onopen();