我不明白在使用烧瓶扩展烧瓶脚本时如何更改全局变量。为了演示我的问题,我开发了以下小型烧瓶应用程序,它将为每个请求调用增加一个全局计数器变量。此外,它还提供了重置全局计数器的重置功能:
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
from flask import Flask
from flask.ext.script import Manager
app = Flask(__name__)
app.debug = True
manager = Manager(app)
counter = 0
@manager.command
@app.route("/reset")
def reset():
global counter
print "Counter before reset:", counter
counter = 0
print "Counter after reset:", counter
return str(counter)
@app.route("/")
def add():
global counter
print "Counter before adding:", counter
counter +=1
print "Counter after adding:", counter
return str(counter)
if __name__ == "__main__":
manager.run()
我使用启动我的烧瓶应用程序python counter.py runserver
当我访问地址 127.0.0.1:5000 时,我看到计数器在增加
Counter before adding: 0
Counter after adding: 1
127.0.0.1 - - [17/Apr/2013 10:09:35] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [17/Apr/2013 10:09:35] "GET /favicon.ico HTTP/1.1" 404 -
Counter before adding: 1
Counter after adding: 2
...
当我访问地址 127.0.0.1:5000/reset 时,我看到计数器已重置
Counter before reset: 4
Counter after reset: 0
127.0.0.1 - - [17/Apr/2013 10:10:39] "GET /reset HTTP/1.1" 200 -
127.0.0.1 - - [17/Apr/2013 10:10:39] "GET /favicon.ico HTTP/1.1" 404 -
但是,当我尝试使用烧瓶脚本扩展提供的管理接口从命令行调用重置方法时,全局计数器变量不会重置:
> python counter.py reset
Counter before reset: 0
Counter after reset: 0
0
我究竟做错了什么?如何使用烧瓶脚本访问和操作全局变量?