从装饰器访问 django 会话
我有一个装饰器,用于我的视图 @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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
视图函数将请求作为第一个参数,因此装饰器也将接收它作为其第一个参数。您只需使用 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.
您可以将请求(或只是会话)作为 参数传递给装饰器。我只是不知道如何将其传递进去。昨晚我试图找出类似的东西。
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.
类似以下内容可以解决您的问题吗:
Will something like the following solve your problem: