python - 如何为我的 Django/Python View 编写装饰器?

标签 python django http request decorator

这是我的看法。基本上,它根据是否登录返回不同的响应。

@check_login()
def home(request):
    if is_logged_in(request): 
        return x
    else:
        return y

这是我的装饰器代码。我只想检查请求是否有标题,如果有,请登录。

#decorator to log the user in if there are headers
def check_login():
    def check_dec(func):
        if request.META['username'] == "blah":
            login(request, user)

    return check_dec

问题是..在这种情况下我不知道如何写一个合适的装饰器!!!论点是什么?有哪些功能?怎么办?

最佳答案

仅使用 @check_login 而不是 check_login() - 否则您的装饰器必须在您执行 home = check_login()(home) 时返回装饰

这是一个示例装饰器:

def check_login(method):
    @functools.wraps(method)
    def wrapper(request, *args, **kwargs):
        if request.META['username'] == "blah"
            login(request, user) # where does user come from?!
        return method(request, *args, **kwargs)
    return wrapper

如果用户名字段设置为“blah”,此装饰器将调用执行您的登录函数,然后调用原始方法。

关于python - 如何为我的 Django/Python View 编写装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4320703/

相关文章:

python - 使用 sklearn 使用卡方核进行多标签预测

python - 如何获取字符串中重复出现的字符的位置?

python - list()连续两次应用于zip对象

django - 无法让 nginx 为收集的静态文件提供服务

Python 'requests' 库 - 定义特定的 DNS?

python - 如何通过 list = None 验证迭代?

python - 无法使用 Django 和 Python 在 URL 查询字符串中传递值

python - 如何使用 Python-Social-auth 和 Django 检索 Facebook 好友的信息

python - 如何让网络服务器响应本地网络之外的请求?

java - 将 ImageIO.read 与重定向 URL 一起使用