我有以下代码:
import datetime
from flask.app import Flask
app = Flask(__name__)
app.config.from_object(__name__)
app.debug = True
def track_time_spent(name):
def decorator(f):
def wrapped(*args, **kwargs):
start = datetime.datetime.now()
ret = f(*args, **kwargs)
delta = datetime.datetime.now() - start
print name, "took", delta.total_seconds(), "seconds"
return ret
return wrapped
return decorator
@app.route('/foo')
@track_time_spent('foo')
def foo():
print "foo"
return "foo"
@app.route('/bar')
@track_time_spent('bar')
def bar():
print "bar"
return "bar"
我无法让 foo 返回“foo”:
$ curl localhost:8888/foo
bar
(flask window)
bar
bar took 8.2e-05 seconds
127.0.0.1 - - [18/Apr/2013 19:21:31] "GET /foo HTTP/1.1" 200 -
$ curl localhost:8888/bar
bar
(flask window)
bar
bar took 3.5e-05 seconds
127.0.0.1 - - [18/Apr/2013 19:21:35] "GET /bar HTTP/1.1" 200 -
这是怎么回事?为什么我的装饰器不起作用?
编辑
我不认为你们似乎能够看到问题所在。
当我有@app.route
before@track_time_spent
时,两种方法都返回 bar。这里的错误是调用 localhost:8888/foo 会导致bar
http 响应和 print 函数。