python Django登录用户跟踪
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Django登录用户跟踪相关的知识,希望对你有一定的参考价值。
from django.utils import timezone
class LastAccessMixin(object):
def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated():
request.user.accessdata.last_access = timezone.now()
request.user.accessdata.save(update_fields=['last_access'])
return super(LastAccessMixin, self).dispatch(request, *args, **kwargs)
# MIXIN USE
# from django.views.generic import TemplateView
# from home.mixins import LastAccessMixin
#
# class IndexView(LastAccessMixin, TemplateView):
# template_name = 'home/index.html'
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_COOKIE_AGE = 24 * 60 * 60 # one day
LAST_ACTIVITY_INTERVAL_SECS = 300
MIDDLEWARE = [
...
'apps.backend.middleware.general.LastUserActivityMiddleware',
...
]
import time
from datetime import datetime, timedelta
from django.conf import settings
class LastUserActivityMiddleware(MiddlewareMixin):
KEY = "last-activity"
def process_view(self, request, view_func, view_args, view_kwargs):
assert hasattr(request, 'user'), 'The UpdateLastActivityMiddleware requires authentication middleware to be installed.'
if request.user.is_authenticated:
last_activity = datetime.fromtimestamp(
request.session.get(self.KEY)
)
too_old_time = datetime.now() - timedelta(
seconds=settings.LAST_ACTIVITY_INTERVAL_SECS
)
if not last_activity or last_activity < too_old_time:
LoggedUser.objects.filter(user=request.user).update(
last_activity=timezone.now()
)
request.session[self.KEY] = time.mktime(
datetime.now().timetuple()
)t('saved: {} ({})'.format(datetime_now,request.session[self.KEY]))
from django.shortcuts import render_to_response
from django.template import RequestContext
from usuarios.models import LoggedUser
def logged(request):
logged_users = LoggedUser.objects.all().order_by('username')
return render_to_response('users/logged.html',
{'logged_users': logged_users},
context_instance=RequestContext(request))
from django.db import models
from django.contrib.auth.signals import user_logged_in, user_logged_out
class LoggedUser(models.Model):
username = models.CharField(max_length=30, primary_key=True)
logued = models.BooleanField(default=True)
last_ip = models.GenericIPAddressField(blank=True, null=True)
last_datetime = models.DateTimeField(auto_now=True)
def __str__(self):
return '{} | Last Login: {} from IP: {}'.format(
self.username,
self.last_datetime,
self.last_ip,
)
def login_user(sender, request, user, **kwargs):
u, created = LoggedUser.objects.get_or_create(username=user.username)
u.logued = True
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
u.last_ip = x_forwarded_for.split(',')[0]
else:
u.last_ip = request.META.get('REMOTE_ADDR')
u.save()
def logout_user(sender, request, user, **kwargs):
try:
u = LoggedUser.objects.get(pk=user.username)
u.logued = False
u.save()
except LoggedUser.DoesNotExist:
pass
user_logged_in.connect(login_user)
user_logged_out.connect(logout_user)
以上是关于python Django登录用户跟踪的主要内容,如果未能解决你的问题,请参考以下文章
059.Python前端Django组件cooki和session
Django之cookie与session
python-django电商项目_20191114
python Django:使用用户名或电子邮件登录
使用 json 在 python / django 中设置用户登录,但不知道从哪里开始
python(Django框架)登录注册案例