You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django会话刷新简化实现咨询:无需逐视图设置方案

Absolutely! Django gives you a couple of clean ways to avoid repeating that request.session.set_expiry(30) line in every view—no more copy-pasting. Let's break down the best approaches for your use case:

1. Create a Reusable Decorator

Since you're already using @login_required, you can build a custom decorator that combines both the login check and session expiry setting. This way you just use one decorator per view instead of two.

First, create a decorators.py file in your app:

from django.contrib.auth.decorators import login_required
from functools import wraps

def login_with_session_expiry(expiry_seconds):
    def decorator(view_func):
        @login_required
        @wraps(view_func)
        def wrapped_view(request, *args, **kwargs):
            request.session.set_expiry(expiry_seconds)
            return view_func(request, *args, **kwargs)
        return wrapped_view
    return decorator

Then use it in your views to replace the duplicate code:

from .decorators import login_with_session_expiry

@login_with_session_expiry(30)
def index(request):
    testvar = "Hi!"
    return render(request, 'testapp/index.html', {'testvar': testvar})

@login_with_session_expiry(30)
def uploadview(request):
    # Your view logic here
    return render(request, 'testapp/upload.html')

This keeps your views clean and centralizes the session expiry logic—if you ever need to adjust the timeout, you just update it in one place (or even pass different values to the decorator per view if needed).

2. Use a Custom Middleware (For Global Application)

If you want this session expiry to apply to all authenticated users automatically (no need to add a decorator to each view), a middleware is the perfect solution. Middleware runs for every request, so you can check if the user is logged in and set the expiry once.

Create a middleware.py file in your app:

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

    def __call__(self, request):
        # Only set expiry if the user is authenticated
        if request.user.is_authenticated:
            request.session.set_expiry(30)
        response = self.get_response(request)
        return response

Then add it to your settings.py under MIDDLEWARE—make sure it comes after the authentication middleware so request.user is properly populated:

MIDDLEWARE = [
    # ... other existing middleware
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'your_app_name.middleware.SessionExpiryMiddleware',  # Add this line
    # ... other existing middleware
]

With this setup, every time an authenticated user makes a request, their session expiry gets reset to 30 seconds. No changes needed to your existing views at all!

Quick Note

Remember that request.session.set_expiry(30) resets the expiry timer on every request—so as long as the user is active (making requests), their session won't expire. This matches the behavior of your original view code.

内容的提问来源于stack exchange,提问作者Marcus Grass

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:00:20