V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Nov 29, 2018 · 3199 views
    This topic created in 2709 days ago, the information mentioned may be changed or developed.
    flag = 0
    
    @web.route('/monitor')
    def monitor():
        """
                display all state
        """
        global flag
        flag += 1
        if flag == 1:
            once = "initonce();"
        else:
            once = "init();"
    

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

    11 replies    2018-11-29 20:59:15 +08:00
    XIVN1987
        2
    XIVN1987  
       Nov 29, 2018
    Class-Based Views
    Trim21
        3
    Trim21  
       Nov 29, 2018 via iPhone
    Redis 之类的 kv 数据库
    fanhaipeng0403
        4
    fanhaipeng0403  
       Nov 29, 2018   ❤️ 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  
       Nov 29, 2018
    bantao
        6
    bantao  
       Nov 29, 2018
    单例类里面做统计
    raysonx
        7
    raysonx  
       Nov 29, 2018
    如果你的程序是多进程的或者在分布式环境下做 load balancing,上述提到的方法只有数据库可用。
    www5070504
        9
    www5070504  
       Nov 29, 2018
    @app.before_request 加上 随便一个文件读写或者 kv 数据库都行
    www5070504
        10
    www5070504  
       Nov 29, 2018
    啊我好像看错了..
    dingyaguang117
        11
    dingyaguang117  
       Nov 29, 2018
    current_app.flag = 0
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1997 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 00:02 · PVG 08:02 · LAX 17:02 · JFK 20:02
    ♥ Do have faith in what you're doing.