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