Python 在不使用全局变量的情况下怎么统计方法运行次数(flask 框架中)?

2018-11-29 15:12:20 +08:00
 wasp
flag = 0

@web.route('/monitor')
def monitor():
    """
            display all state
    """
    global flag
    flag += 1
    if flag == 1:
        once = "initonce();"
    else:
        once = "init();"

大致代码是这样,请问怎么改可以不使用全局变量进行判断。

2691 次点击
所在节点    Python
11 条回复
Jat001
2018-11-29 15:13:09 +08:00
XIVN1987
2018-11-29 15:17:41 +08:00
Class-Based Views
Trim21
2018-11-29 15:18:10 +08:00
Redis 之类的 kv 数据库
fanhaipeng0403
2018-11-29 15:18:24 +08:00
def counted(f):
def wrapped(*args, **kwargs):
wrapped.calls += 1
return f(*args, **kwargs)
wrapped.calls = 0
return wrapped



@counted
def foo():
print('1')


foo()
foo()
foo()
foo()
foo()
foo()

print(foo.calls)
fanhaipeng0403
2018-11-29 15:19:14 +08:00
bantao
2018-11-29 15:23:20 +08:00
单例类里面做统计
raysonx
2018-11-29 15:27:43 +08:00
如果你的程序是多进程的或者在分布式环境下做 load balancing,上述提到的方法只有数据库可用。
ltoddy
2018-11-29 15:41:42 +08:00
www5070504
2018-11-29 16:01:39 +08:00
@app.before_request 加上 随便一个文件读写或者 kv 数据库都行
www5070504
2018-11-29 16:02:33 +08:00
啊我好像看错了..
dingyaguang117
2018-11-29 20:59:15 +08:00
current_app.flag = 0

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/512730

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX