V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
wasp
V2EX  ›  Python

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

  •  
  •   wasp · 2018-11-29 15:12:20 +08:00 · 2660 次点击
    这是一个创建于 1946 天前的主题,其中的信息可能已经有所发展或是发生改变。
    flag = 0
    
    @web.route('/monitor')
    def monitor():
        """
                display all state
        """
        global flag
        flag += 1
        if flag == 1:
            once = "initonce();"
        else:
            once = "init();"
    

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

    11 条回复    2018-11-29 20:59:15 +08:00
    XIVN1987
        2
    XIVN1987  
       2018-11-29 15:17:41 +08:00
    Class-Based Views
    Trim21
        3
    Trim21  
       2018-11-29 15:18:10 +08:00 via iPhone
    Redis 之类的 kv 数据库
    fanhaipeng0403
        4
    fanhaipeng0403  
       2018-11-29 15:18:24 +08:00   ❤️ 3
    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
        5
    fanhaipeng0403  
       2018-11-29 15:19:14 +08:00
    bantao
        6
    bantao  
       2018-11-29 15:23:20 +08:00
    单例类里面做统计
    raysonx
        7
    raysonx  
       2018-11-29 15:27:43 +08:00
    如果你的程序是多进程的或者在分布式环境下做 load balancing,上述提到的方法只有数据库可用。
    ltoddy
        8
    ltoddy  
       2018-11-29 15:41:42 +08:00
    www5070504
        9
    www5070504  
       2018-11-29 16:01:39 +08:00
    @app.before_request 加上 随便一个文件读写或者 kv 数据库都行
    www5070504
        10
    www5070504  
       2018-11-29 16:02:33 +08:00
    啊我好像看错了..
    dingyaguang117
        11
    dingyaguang117  
       2018-11-29 20:59:15 +08:00
    current_app.flag = 0
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   994 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 68ms · UTC 22:17 · PVG 06:17 · LAX 15:17 · JFK 18:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.