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 pass def 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
提交
取消