我有login_required装饰器,如下所示:

def login_required(function):
  """ Decorator to check Logged in users."""
  def check_login(self, *args, **kwargs):
    if not self.auth.get_user_by_session():
      self.redirect('/_ah/login_required')
    else:
      return function(self, *args, **kwargs)
  return check_login


现在,我有了一个Page(由单独的Handler呈现),其中有一个供用户上传供访客和用户查看的图像的选项。表单发布后,将由另一个使用Handler装饰器的@login_required处理。

我要实现的是传递一个continue_url变量,该变量可以在重定向时在check_login函数中使用,以便用户登录后重定向到同一页面。

最佳答案

因此,基本上,听起来您想在使用时将参数传递给装饰器。 Python确实支持这一点。基本思想是@decorated(argument) def foo(...)等同于def foo(...); foo = decorated(argument)(foo)

因此,您需要使decorated成为decorated(argument)可以修饰foo的东西。有几种解决方法。这是一个-用decorated方法使__call__成为一个类,以便decorated(argument)是可调用对象,该对象存储argument并在调用时使用它:

class decorator(object):
    def __init__(argument):
        self.argument = argument

    def __call__(self, wrapped):
        def wrapper(args_for_wrapped):
            do_something_with(self.argument)
            wrapped(args_for_wrapped)
            whatever_else_this_needs_to_do()
        return wrapper


这也可以通过使用普通函数(以及附加的嵌套级别)以及涉及functools.partial等的技巧来实现。

关于python - 如何将继续URL传递到需要登录的装饰器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10675307/

10-10 11:26