瓶框架和OOP,使用方法代替功能

时间:2012-01-04 10:53:24

标签: python oop class methods bottle

我用Bottle做了一些编码。它非常简单,符合我的需求。但是,当我试图将应用程序包装到一个类中时,我坚持了下来:

import bottle
app = bottle

class App():
    def __init__(self,param):
        self.param   = param

    # Doesn't work
    @app.route("/1")
    def index1(self):
        return("I'm 1 | self.param = %s" % self.param)

    # Doesn't work
    @app.route("/2")
    def index2(self):
        return("I'm 2")

    # Works fine
    @app.route("/3")
    def index3():
        return("I'm 3")

是否可以在Bottle中使用方法而不是函数?

5 个答案:

答案 0 :(得分:39)

您的代码无效,因为您尝试路由到非绑定方法。非绑定方法没有self的引用,如果尚未创建App的实例,它们怎么可能?

如果要路由到类方法,首先必须初始化类,然后bottle.route()初始化该对象上的方法,如下所示:

import bottle        

class App(object):
    def __init__(self,param):
        self.param   = param

    def index1(self):
        return("I'm 1 | self.param = %s" % self.param)

myapp = App(param='some param')
bottle.route("/1")(myapp.index1)

如果要在处理程序附近粘贴路径定义,可以执行以下操作:

def routeapp(obj):
    for kw in dir(app):
        attr = getattr(app, kw)
        if hasattr(attr, 'route'):
            bottle.route(attr.route)(attr)

class App(object):
    def __init__(self, config):
        self.config = config

    def index(self):
        pass
    index.route = '/index/'

app = App({'config':1})
routeapp(app)

不要在bottle.route()中执行App.__init__()部分,因为您将无法创建两个App类的实例。

如果您喜欢装饰器的语法而不是设置属性index.route=,那么您可以编写一个简单的装饰器:

def methodroute(route):
    def decorator(f):
        f.route = route
        return f
    return decorator

class App(object):
    @methodroute('/index/')
    def index(self):
        pass

答案 1 :(得分:24)

下面很适合我:) 面向对象,易于遵循。

from bottle import Bottle, template

class Server:
    def __init__(self, host, port):
        self._host = host
        self._port = port
        self._app = Bottle()
        self._route()

    def _route(self):
        self._app.route('/', method="GET", callback=self._index)
        self._app.route('/hello/<name>', callback=self._hello)

    def start(self):
        self._app.run(host=self._host, port=self._port)

    def _index(self):
        return 'Welcome'

    def _hello(self, name="Guest"):
        return template('Hello {{name}}, how are you?', name=name)

server = Server(host='localhost', port=8090)
server.start()

答案 2 :(得分:24)

您必须扩展Bottle课程。它的实例是WSGI Web应用程序。

from bottle import Bottle

class MyApp(Bottle):
    def __init__(self, name):
        super(MyApp, self).__init__()
        self.name = name
        self.route('/', callback=self.index)

    def index(self):
        return "Hello, my name is " + self.name

app = MyApp('OOBottle')
app.run(host='localhost', port=8080)

大多数例子都在做,包括之前提供给这个问题的答案,都是重复使用&#34;默认应用程序&#34;,而不是创建自己的应用程序,而不是使用面向对象和继承的便利。

答案 3 :(得分:3)

我接受了@Skirmantas的回答并对其进行了一些修改以允许在装饰器中使用关键字参数,如方法,跳过等:

def routemethod(route, **kwargs):
    def decorator(f):
        f.route = route
        for arg in kwargs:
            setattr(f, arg, kwargs[arg])
        return f
    return decorator

def routeapp(obj):
    for kw in dir(obj):
        attr = getattr(obj, kw)
        if hasattr(attr, "route"):
            if hasattr(attr, "method"):
                method = getattr(attr, "method")
            else:
                method = "GET"
            if hasattr(attr, "callback"):
                callback = getattr(attr, "callback")
            else:
                callback = None
            if hasattr(attr, "name"):
                name = getattr(attr, "name")
            else:
                name = None
            if hasattr(attr, "apply"):
                aply = getattr(attr, "apply")
            else:
                aply = None
            if hasattr(attr, "skip"):
                skip = getattr(attr, "skip")
            else:
                skip = None

            bottle.route(attr.route, method, callback, name, aply, skip)(attr)

答案 4 :(得分:3)

尝试这个,为我工作,文档开始也相当不错......

https://github.com/techchunks/bottleCBV