In django : how to renew expiry date for current session?

坚强是说给别人听的谎言 提交于 2019-12-05 01:25:48

问题


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


回答1:


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)



回答2:


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',
    ...
]



回答3:


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.



来源:https://stackoverflow.com/questions/3044799/in-django-how-to-renew-expiry-date-for-current-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!