【问题标题】:Is it possible to mark a method with a route in Flask? [duplicate]是否可以在 Flask 中用路由标记方法? [复制]
【发布时间】:2016-10-04 13:28:06
【问题描述】:

可以继承Flask:

from flask import Flask

class MyServer(Flask):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def my_cool_method(self):
        print("About to do some crazy productive work!")

通过这样做,可以创建一个MyServer 对象并定义一个路由,该路由在命中时调用一个方法。

my_server = MyServer(__name__)

@my_server.route("/my_cool_endpoint")
def my_cool_endpoint():
    my_server.my_cool_method()

有没有什么可能的方法可以去掉这个看似不必要(而且相当不可持续)的步骤,并简单地用路线装饰一个方法

我的伪代码类似于...

#!/usr/bin/env python3

from flask import Flask

class MyServer(Flask):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    @self.route("/my_cool_endpoint")
    def my_cool_method(self):
        print("About to do some crazy productive work!")

if __name__ == "__main__":
    my_server = MyServer(__name__)
    # We can now hit 127.0.0.1:8080/my_cool_endpoint... hopefully
    my_server.run(port=8080)

我的动机是简单地run 对象并让端点受到攻击,在每次 API 调用时修改对象的状态。

如果这不可能完全按照我的描述进行,那么实现我的目标最不冒犯的方式是什么?

【问题讨论】:

  • 对不起,这有点难以理解。为什么简单的控制器不适合你?

标签: python python-3.x flask


【解决方案1】:

routeFlask 类的一个方法,因此它实际上需要应用程序实例作为第一个参数(当您执行@app.route 时会传入该参数)。由于类的所有方法(修饰与否)都在“编译”时进行评估,因此不能按照您描述的方式完成(或者可以,但需要一些严肃的魔法)。你总是可以这样做:

class MyApp(Flask):
    def __init__(self, *args, **kwargs):
        self.count = 0
        super(MyApp, self).__init__(*args, **kwargs)

        @self.route('/')
        def index():
            self.count += 1
            print self.count
            return 'foo'

self 可以引用与__init__ 相同的self,因为形成了闭包。

但是由于 Flask 的context locals,在 Flask 中的对象中保持状态并不是那么好。请改用会话。

另外,我想你要找的是class-based views

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多