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

36 python oop methods class 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")
Run Code Online (Sandbox Code Playgroud)

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

Ski*_*Ski 41

您的代码不起作用,因为您尝试路由到非绑定方法.非绑定方法没有引用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)
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

不要进入该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
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`bottle.route(attr.route,attr)`将不会按预期工作; 你想要`bottle.route(attr.route)(attr)`(因为bottle.route()是一个装饰器,它返回一个可调用的,然后使用`(attr)`). (3认同)

Mat*_*t H 25

下面很适合我:)相当对象,易于遵循.

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()
Run Code Online (Sandbox Code Playgroud)

  • 该解决方案使用组合而不是继承,这在 OOP 中非常好。引用维基百科上的说法:优先考虑组合而不是继承是一个设计原则,它赋予了设计更高的灵活性。我 (2认同)

jpc*_*cgt 25

你必须扩展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)
Run Code Online (Sandbox Code Playgroud)

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