Django - 会话过期更新

Django - Session expiration renewal

我正在为一个关于会话的问题而苦恼。

我想知道如果用户在一段时间内(例如 15 天)没有尝试连接到网站,如何使会话过期。 换句话说,我想在每次 he/she 连接到该站点时更新用户会话的到期日期。

我翻了很多网站,但找不到任何有价值的例子。

在您的 settings.py 中设置 SESSION_COOKIE_AGE

SESSION_COOKIE_AGE = 15 * 60 # 15 Minutes

在文档中了解更多信息https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-SESSION_COOKIE_AGE

我目前在我的一个系统中实施的一个很好的解决方案,如果您希望您的会话在每次请求时自动更新,那就是编写中间件来更改会话的到期时间,以便在您的任何视图中延长需要。

注意:此解决方案确实为每个请求进行 2 个数据库查询。 1 个用于读取,1 个用于更新。这是一个非常小的开销(最多使用调试工具栏调用通常只有几毫秒),但它在那里。

例如:

from functools import wraps
from [project] import settings

class CookieMiddleware(object):
    """
    This middleware sets the login cookie to update timeout on every request
    """

    def __init__(self, get_response):
        self.get_response = get_response

    @staticmethod
    def process_view(request, view_func, args, kwargs):
        # ensure that we don't want to exclude this from running
        if getattr(view_func, 'cookie_not_important', False):
            print('cookie not important:', view_func.__name__)
            return None

        # the cookie is set, let's now set a new expire time to 30 minutes from now
        print('cookie expiry changed:', view_func.__name__)
        # it is probably smartest to grab this value back from settings
        expire_time = settings.SESSION_COOKIE_AGE
        # expire_time = 30 * 60
        request.session.set_expiry(expire_time)
        return view_func(request, *args, **kwargs)

    def __call__(self, request):
        response = self.get_response(request)
        return response


def cookie_not_important(view_func):
    """
    Decorator used to allow the exclusion of the cookie time being reset
    :param view_func: The view being wrapped
    :return:
    """

    def view_being_wrapped(*args, **kwargs):
        return view_func(*args, **kwargs)

    view_being_wrapped.cookie_not_important = True
    return wraps(view_func)(view_being_wrapped)

现在您可以登录并点击任何未被 @cookie_not_important 包裹的视图,过期时间将根据 settings.py

中的当前值重置

为了完整起见,视图的包装方式如下:

from django.urls import reverse

@cookie_not_important
def logout(request):
    del request.session
    return redirect(reverse('some_view_name'))

这个库可能会有帮助,它会在给定时间后注销非活动会话 https://github.com/yourlabs/django-session-security