python - flask 如何统计每次访问的耗时(采用装饰器)
本文介绍了python - 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 的问题』。
解决方案
你没把函数给返回啊。。
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
-。-
这篇关于python - flask 如何统计每次访问的耗时(采用装饰器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文