Bottle 框架和 OOP,使用方法而不是函数 [英] Bottle framework and OOP, using method instead of function

查看:19
本文介绍了Bottle 框架和 OOP,使用方法而不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用 Bottle 编写了一些代码.这真的很简单,符合我的需求.但是,当我尝试将应用程序包装到一个类中时,我得到了坚持:

I've done some coding with Bottle. It's really simple and fits my needs. However, I got stick when I tried to wrap the application into a class :

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 中使用方法而不是函数?

Is it possible to use methods instead of functions in Bottle?

推荐答案

您的代码不起作用,因为您正试图路由到非绑定方法.非绑定方法没有对 self 的引用,如果没有创建 App 的实例,它们怎么可能?

Your code does not work because you are trying to route to non-bound methods. Non-bound methods do not have a reference to self, how could they, if instance of App has not been created?

如果你想路由到类方法,你首先必须初始化你的类,然后 bottle.route() 像这样:

If you want to route to class methods, you first have to initialize your class and then bottle.route() to methods on that object like so:

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)

如果你想在处理程序附近粘贴路由定义,你可以这样做:

If you want to stick routes definitions near the handlers, you can do something like this:

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)

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

Don't do the bottle.route() part in App.__init__(), because you won't be able to create two instances of App class.

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

If you like the syntax of decorators more than setting attribute index.route=, you can write a simple decorator:

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

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

这篇关于Bottle 框架和 OOP,使用方法而不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆