【问题标题】:Python Decorators and ClassesPython 装饰器和类
【发布时间】:2014-02-16 10:59:53
【问题描述】:

我正在使用 Flask 和 Flask-Login 开发 Web 服务器。它一直在工作,直到我需要将它移到课堂上。由于装饰器而损坏:在我有代码之前

login_manager = LoginManager(app)
...
@login_required
def control_panel():
    return render_template(...)

但现在变成了:

class webserver:
    def __init__(self):
        self.login_manager = LoginManager(app)

    ...
    @login_required
    def control_panel(self):
        return self.render_template(...)

问题是我真的需要写,

@self.login_required

但它不是有效的语法。我该如何克服这个问题?

谢谢!

【问题讨论】:

  • 为什么要写@self
  • 因为它无法识别 login_required,因为它是 login_manager 的一部分,变成了 self.login_manager
  • 这毫无意义。只有 self 如果它是类的属性,它不是。
  • 我不能使用@login_required,因为它没有被定义。
  • 那也许你需要导入它。

标签: python class flask decorator


【解决方案1】:

我不确定你的 LoginManager 是如何创建装饰器的,但你可以让它像这样工作:

class LoginManager:
    def __init__(self, app):
        pass

    @staticmethod
    def login_required(func):
        def inner(*args, **kwargs):
            print "login_required: before"
            func(*args, **kwargs)
            print "login_required: after"
        return inner


class Webserver:
    def __init__(self):
        self.login_manager = LoginManager(app)

    @LoginManager.login_required
    def control_panel(self):
        print "control_panel: called"


app = {}
ws = Webserver()
ws.control_panel()

输出:

login_required: before
control_panel: called
login_required: after

【讨论】:

  • 一些反馈会很好。这对你有用吗?如果不是,为什么?
  • 对不起!我不再为上课方式而烦恼,因为它太复杂了。它像以前一样工作。不过还是谢谢!
猜你喜欢
  • 2011-03-23
  • 2011-04-28
  • 1970-01-01
  • 2023-03-14
  • 2015-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 2010-12-19
相关资源
最近更新 更多