Changing a global variable externally in a Flask-based Python web application

I do not understand how to change a global variable when using a bulb extension bulb - script. To demonstrate my problem, I developed the following application for small flasks, which will increase the global counter variable for each request. In addition, it offers a reset function to reset the global counter:

# -*- 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() 

I run my flask using python counter.py runserver

When I access the address 127.0.0.1∗000, I see that the counter is incrementing

 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 ... 

When I access the address 127.0.0.1►000/ reset, I see that the reset counter

 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 - 

However, when I try to call the reset method from the command line using the management interface provided by the flask-script extension, the global counter variable does not reset:

 > python counter.py reset Counter before reset: 0 Counter after reset: 0 0 

What am I doing wrong? How can I access and manipulate a global variable using a script flag?

+6
source share
1 answer

Python global variables, such as counter , live in the memory space of the operating system process. Each process of starting and stopping (application, command, etc.) gets its own memory pie.

When python counter.py reset starts, it starts a new process with its own memory space and variables. The reset variable runs against this process, not the process executed by the web server.

To properly reset a variable

  • Store the variable outside the process memory space (e.g. in memcached, database)

  • Create a command that calls the web server process via a special view URL using wget, curl, urllib or the like, and this view resets the variable in the process memory space

+7
source

All Articles