python3 + flask
因为 sql 特别慢,想打一个 log 看下每次访问的耗时,顺便学一下装饰器的使用,果然跳坑:
代码如下:
def cost_count(func): @wraps(func) def wraper(*args, **kw): a = time.time() func(*args, **kw) # return func(*args, **kw) print(time.time()-a) return wraper @app.route("/view/", methods=['GET']) @cost_count def page_view(slug): return render_template("view.html",entry=entry)
问题出在被注释的这一行:
假如如上所示,func 只是调用,而不 return,确实能在后台打印出请求的耗时,但是页面打不开:网页上报错,提示没有返回内容。
假如 func 前面加上 return,网页能够正常打开,但是耗时就打印不出来了。
下面的代码虽然是调通顺了,但是觉得太诡异了:
def cost_count(func): @wraps(func) def wraper(*args, **kw): a = time.time() th = threading.Thread(target=func, args=(*args) th.setDaemon(True) th.start() th.join() print(time.time()-a) return wraper
所以最后问题是:
使用装饰器统计请求耗时时,如何解决 『看似必须 return 的问题』。
你没把函数给返回啊。。
def cost_count(func): @wraps(func) def wraper(*args, **kwargs): start = time.time() t = func(*args, **kwargs) logging.info("%s tooks time: %f", func.__name__, time.time()-start) return t return wraper
-。-