从装饰器访问 django 会话

发布于 2024-08-28 00:58:51 字数 432 浏览 10 评论 0原文

我有一个装饰器,用于我的视图 @valid_session

from django.http import Http404

def valid_session(the_func):
"""
function to check if the user has a valid session
"""
def _decorated(*args, **kwargs):        
    if ## check if username is in the request.session:
        raise Http404('not logged in.')
    else:
        return the_func(*args, **kwargs)
return _decorated

我想在我的装饰器中访问我的会话。当用户登录时,我将用户名放入我的会话中。

I have a decorator that I use for my views @valid_session

from django.http import Http404

def valid_session(the_func):
"""
function to check if the user has a valid session
"""
def _decorated(*args, **kwargs):        
    if ## check if username is in the request.session:
        raise Http404('not logged in.')
    else:
        return the_func(*args, **kwargs)
return _decorated

I would like to access my session in my decoartor. When user is logged in, I put the username in my session.

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

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

发布评论

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

评论(3

饭团 2024-09-04 00:58:52

视图函数将请求作为第一个参数,因此装饰器也将接收它作为其第一个参数。您只需使用 request.session 即可将会话拉出。

The view function takes the request as the first parameter, so the decorator will receive it as its first parameter as well. You can pull the session out of it with just request.session.

那小子欠揍 2024-09-04 00:58:52

您可以将请求(或只是会话)作为 参数传递给装饰器。我只是不知道如何将其传递进去。昨晚我试图找出类似的东西。

You could pass the request (or just the session) in as a parameter to the decorator. I just don't know how to get at it to pass it in. I was trying to figure out something similar last night.

书间行客 2024-09-04 00:58:51

类似以下内容可以解决您的问题吗:

def valid_session(func):
    def decorated(request, *args, **kwargs):
        print request.session
        return func(request, *args, **kwargs)
    return decorated

Will something like the following solve your problem:

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