在 django 中:如何更新当前会话的到期日期?

发布于 2024-09-06 08:52:31 字数 46 浏览 5 评论 0原文

我有一个用户登录。 我如何延长/更新从请求中收到的会话的到期日期? 提前致谢!

I have a user logged in.
How can i extend/renew expiry date of session received from the request ?
Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

标点 2024-09-13 08:52:31

没有必要为此制作自定义中间件。

设置 SESSION_SAVE_EVERY_REQUEST = True 将导致 Django 现有的 SessionMiddleware 完全按照您的要求执行。

它有这样的代码:

if modified or settings.SESSION_SAVE_EVERY_REQUEST:
    if request.session.get_expire_at_browser_close():
        max_age = None
        expires = None
    else:
        max_age = request.session.get_expiry_age()
        expires_time = time.time() + max_age
        expires = cookie_date(expires_time)
    # Save the session data and refresh the client cookie.
    # Skip session save for 500 responses, refs #3881.
    if response.status_code != 500:
        request.session.save()
        response.set_cookie(settings.SESSION_COOKIE_NAME,
                request.session.session_key, max_age=max_age,
                expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                path=settings.SESSION_COOKIE_PATH,
                secure=settings.SESSION_COOKIE_SECURE or None,
                httponly=settings.SESSION_COOKIE_HTTPONLY or None)

It's not necessary to make a custom middleware for this.

Setting SESSION_SAVE_EVERY_REQUEST = True will cause Django's existing SessionMiddleware to do exactly what you want.

It has this code:

if modified or settings.SESSION_SAVE_EVERY_REQUEST:
    if request.session.get_expire_at_browser_close():
        max_age = None
        expires = None
    else:
        max_age = request.session.get_expiry_age()
        expires_time = time.time() + max_age
        expires = cookie_date(expires_time)
    # Save the session data and refresh the client cookie.
    # Skip session save for 500 responses, refs #3881.
    if response.status_code != 500:
        request.session.save()
        response.set_cookie(settings.SESSION_COOKIE_NAME,
                request.session.session_key, max_age=max_age,
                expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                path=settings.SESSION_COOKIE_PATH,
                secure=settings.SESSION_COOKIE_SECURE or None,
                httponly=settings.SESSION_COOKIE_HTTPONLY or None)
笑红尘 2024-09-13 08:52:31

这是一些扩展经过身份验证的用户会话的中间件。如果距离会话 expiry_date 不到 30 天,它会将会话延长 60 天,从而使他们保持永久登录状态。

custom_middleware.py:

from datetime import timedelta

from django.utils import timezone


EXTENDED_SESSION_DAYS = 60
EXPIRE_THRESHOLD = 30
class ExtendUserSession(object):
    """
    Extend authenticated user's sessions so they don't have to log back in
    every 2 weeks (set by Django's default `SESSION_COOKIE_AGE` setting). 
    """
    def process_request(self, request):
        # Only extend the session for auth'd users
        if request.user.is_authenticated():
            now = timezone.now()

            # Only extend the session if the current expiry_date is less than 30 days from now
            if request.session.get_expiry_date() < now + timedelta(days=EXPIRE_THRESHOLD):
                request.session.set_expiry(now + timedelta(days=EXTENDED_SESSION_DAYS))

然后,您需要在 Django 的 SessionMiddleware 之后添加此自定义中间件,因此您的设置文件应如下所示:

project/settings.py:

MIDDLEWARE_CLASSES = [
    ...
    'django.contrib.sessions.middleware.SessionMiddleware',
    'project.custom_middleware.ExtendUserSession',
    ...
]

Here's some middleware that extends an authenticated user's session. It essentially keeps them permanently logged in by extending their session another 60 days if their session expiry_date is less than 30 days away.

custom_middleware.py:

from datetime import timedelta

from django.utils import timezone


EXTENDED_SESSION_DAYS = 60
EXPIRE_THRESHOLD = 30
class ExtendUserSession(object):
    """
    Extend authenticated user's sessions so they don't have to log back in
    every 2 weeks (set by Django's default `SESSION_COOKIE_AGE` setting). 
    """
    def process_request(self, request):
        # Only extend the session for auth'd users
        if request.user.is_authenticated():
            now = timezone.now()

            # Only extend the session if the current expiry_date is less than 30 days from now
            if request.session.get_expiry_date() < now + timedelta(days=EXPIRE_THRESHOLD):
                request.session.set_expiry(now + timedelta(days=EXTENDED_SESSION_DAYS))

You will then need to add this custom middleware after Django's SessionMiddleware, so your settings file should look like:

project/settings.py:

MIDDLEWARE_CLASSES = [
    ...
    'django.contrib.sessions.middleware.SessionMiddleware',
    'project.custom_middleware.ExtendUserSession',
    ...
]
花落人断肠 2024-09-13 08:52:31

设置 SESSION_COOKIE_AGE 就是为此目的而设计的我相信。登录后,在此期间自动设置 cookie。

您还可以使用 SESSION_SAVE_EVERY_REQUEST 设置。

setting SESSION_COOKIE_AGE is designed for that purpose I believe. After login cookie is set automatically for this period.

You can also save session cookie on every request by using SESSION_SAVE_EVERY_REQUEST setting.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文