我想创建自己的decorotar,它将从Bottle框架中“扩展”@route装饰器。我有sementic的问题。这段代码不起作用,我不知道如何修复它。
from bottle import route, run
class router(object):
def __init__(self, f):
self.f = f
def __call__(self, *args):
self.f(*args)
@router('/hello')
def hello():
return "Hello World!"
run(host='localhost', port=8080, debug=True)
编辑: 第二次尝试:
from bottle import Bottle
class B(Bottle):
def route(self,*args):
def f(*args):
print "My Text" #This dosen't print
super(B, self).route(*args)
return f
b = B()
@b.route('/hello')
def hello():
return "Hello World!x"
b.run(host='localhost', port=8080, debug=True)
也不会工作。
答案 0 :(得分:0)
当我偶然发现此问题以尝试解决类似问题时,我发现您的代码中存在多个问题:
*args
; 这是固定版本(python 3):
from bottle import Bottle
class B(Bottle):
def route(self, *rt_args):
def wrapper(func): # <<-- your decorator shall take the function as argument
print(f"registering {func.__name__} with {rt_args}")
super(B, self).route(*rt_args, callback=func) # <<-- register the function!
return func
return wrapper
b = B()
@b.route('/hello')
def hello():
return "hello world!"
b.run(host='localhost', port=8080, debug=True)
此后对我来说效果很好,打印语句在终端中可见:
(.env) joel@joel-T470s:~/......$ python3 test-bottle.py
registering hello with ('/hello',)
Bottle v0.12.18 server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.
127.0.0.1 - - [19/Apr/2020 10:19:34] "GET /hello HTTP/1.1" 200 12
这个主题在a similar questions中得到了一定的回答。