python - 从装饰器访问 django session

标签 python django decorator django-sessions

我有一个用于我的 View 的装饰器@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

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

最佳答案

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

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

关于python - 从装饰器访问 django session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2613679/

相关文章:

python - 在 vim 中跳转到下一个 python 类或函数

python装饰器修改当前范围内的变量

python - “makemigrations”要求使用非抽象模型继承的默认值

python - Django,覆盖多对多字段ModelManager

javascript - 在 Django 中使用 ajax POST 请求

python - 问题: how to reference to objects/variables created in decorator from injected method?

python - 如何使类属性不可变?

python - 如何将 "inject"内存中的 SQLAlchemy sqlite3 数据库放入 Flask test_client?

python - 在Python中使用嵌套for循环加载字典

Python 无法打开符号链接(symbolic link)文件