flask 如何统计每次访问的耗时(采用装饰器)
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/<slug>", 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 的问题』。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你没把函数给返回啊。。
-。-