Django中views如何设置全局变量
4 回答
侃侃尔雅
TA贡献1801条经验 获得超16个赞
问题在于test = 1实际上是定义了一个局部变量test,它隐藏了全局作用域中的test变量。
要指明使用全局的test变量,需要使用global关键字。
| 12345678910111213 | from django.http import HttpResponse test = 0 def a(request): global test test = 1 return HttpResponse('view a: test = %d' % test) def b(request): global test test += 1 return HttpResponse('view b: test = %d' % test) |
德玛西亚99
TA贡献1770条经验 获得超3个赞
简单使用的话,不要使用整数这种不可变的对象类型。使用列表或者字典。比如:
| 1234567 | test = [0]def a(request): test[0] += 1 passdef b(request): print(test[0]) pass |
狐的传说
TA贡献1804条经验 获得超3个赞
你一刷新页面,这个方法就执行了,所以里面的进程就执行了啊。
按照你的需求,你可以给那个按钮增加一个参数,比如
| 1 | <a href="url?go=1">start</a> |
| 12345678910 | def mysql(request): go = request.GET.get('go', 0) if go == 1: mysql_version = "5.1.73" mysql_port = os.popen("netstat -ntlp | grep mysqld | awk '{print $4}' | awk -F ':' '{print $NF}'").read() mysql_start = os.popen("/etc/rc.d/init.d/mysqld start >>/dev/null").read() mysql_stop = os.popen("/etc/rc.d/init.d/mysqld stop >>/dev/null").read() eturn render_to_response('mysql.html',locals()) |
添加回答
举报
0/150
提交
取消
