在django rest框架中获取会话时间

时间:2018-06-18 18:40:35

标签: python django django-rest-framework

我是一个真正的新鸟到python和使用Django休息框架。我已按照教程" http://www.django-rest-framework.org/tutorial/quickstart"并为admin创建了一个登录注销页面。我想跟踪会话时间或基本上是用户登录的时间,我尝试通过遵循这些教程来做同样的事情,如{39} https://github.com/GetBlimp/django-rest-framework-jwt'但我认为我偏离了我的想法,请提出任何教程或任何帮助。 感谢

1 个答案:

答案 0 :(得分:1)

我认为这是{em>不存储在Session中,但没有什么能阻止我们自己存储它。

我们可以例如构建模型UserSession

# models.py

from django.conf import settings
from django.db import models
from django.contrib.sessions.models import Session

class UserSession(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    session = models.OneToOneField(Session, on_delete=models.CASCADE)

    session_start = models.DateTimeField(auto_now_add=True)

当然,现在我们仍然需要确保构造这样的对象,但是我们可以为登录过程创建一个 hook

from django.contrib.auth import user_logged_in
from django.dispatch.dispatcher import receiver

@receiver(user_logged_in)
def register_session(sender, user, request, **kwargs):

    # save current session
    request.session.save()

    # create a link from the user to the current session (for later usage)
    UserSession.objects.get_or_create(
        user=user,
        session=Session.objects.get(pk=request.session.session_key)
    )

然后我们可以获得会话开始的时间:

from datetime import datetime

def some_view(request):
    try:
        session_started = request.session.usersession.session_start
    except UserSession.DoesNotExist:
        # ...
        # handle the case when the UserSession is not present
        pass
    else:
        session_duration = datetime.now() - session_started
        # ...
        pass