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
wly
V2EX  ›  Python

python web.py 下的全局变量的问题

  •  1
     
  •   wly · Aug 5, 2016 · 4639 views
    This topic created in 3555 days ago, the information mentioned may be changed or developed.
    
    import threading
    import time
    import web
    
    global bianliang
    bianliang=0
    
    class Test:
        global bianliang
        def GET(self):
            return str(bianliang)
    
    def _listen_yushui():
        while True:
            time.sleep(2)
            global bianliang
            print bianliang
    
    def _add():
        while True:
            time.sleep(2)
            global bianliang
            bianliang=bianliang+1
    urls=(
        '/test','Test'
    )
    application = web.application(urls, globals())
    
    if __name__ == "__main__":
        yushui = threading.Thread(target=_listen_yushui)
        yushui.setDaemon(True)
        yushui.start()
        add = threading.Thread(target=_add)
        add.setDaemon(True)
        add.start()
        application.run()
    

    上面的代码在运行时,控制台输出可以看到 bianliang 的值在不断的增加;但是发送一个网络请求'your_url/test',请求到的结果却是 bianliang 的初始值 0 ,这是为什么?

    5 replies    2022-11-15 17:07:50 +08:00
    iii
        1
    iii  
       Aug 5, 2016
    控制台输出和 webserver 属于不同进程
    vmebeh
        2
    vmebeh  
       Aug 5, 2016 via iPhone
    用过 web.var_name="value"
    wly
        3
    wly  
    OP
       Aug 5, 2016
    @vmebeh 感谢,已成功
    zhuangzhuang1988
        4
    zhuangzhuang1988  
       Aug 5, 2016
    redis 上.
    HankLu
        5
    HankLu  
       Nov 15, 2022
    @wly 请问怎么改的?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   836 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 21:58 · PVG 05:58 · LAX 14:58 · JFK 17:58
    ♥ Do have faith in what you're doing.