Bottle方法框架和OOP,使用方法代替函数
我已经用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中使用方法而不是函数?
-
您的代码不起作用,因为您尝试路由到非绑定方法。非绑定方法没有对的引用
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