全局变量在Python / Django中不起作用?

时间:2012-11-16 06:31:10

标签: python django

这是我的views.py:

from django.shortcuts import render_to_response
from django.template import RequestContext
import subprocess

globalsource=0
def upload_file(request):
    '''This function produces the form which allows user to input session_name, their remote host name, username 
    and password of the server. User can either save, load or cancel the form. Load will execute couple Linux commands
    that will list the files in their remote host and server.'''

    if request.method == 'POST':    
        # session_name = request.POST['session']
        url = request.POST['hostname']
        username = request.POST['username']
        password = request.POST['password']

        globalsource = str(username) + "@" + str(url)

        command = subprocess.Popen(['rsync', '--list-only', globalsource],
                           stdout=subprocess.PIPE,
                           env={'RSYNC_PASSWORD': password}).communicate()[0]

        result1 = subprocess.Popen(['ls', '/home/'], stdout=subprocess.PIPE).communicate()[0]
        result = ''.join(result1)

        return render_to_response('thanks.html', {'res':result, 'res1':command}, context_instance=RequestContext(request))

    else:
        pass
    return render_to_response('form.html', {'form': 'form'},  context_instance=RequestContext(request))

    ##export PATH=$RSYNC_PASSWORD:/usr/bin/rsync

def sync(request):
    """Sync the files into the server with the progress bar"""
    finalresult = subprocess.Popen(['rsync', '-zvr', '--progress', globalsource, '/home/zurelsoft/R'], stdout=subprocess.PIPE).communicate()[0]
    return render_to_response('synced.html', {'sync':finalresult}, context_instance=RequestContext(request))

问题出在sync()视图中。不采用upload_file的全局变量值,但在同步视图中采用globalvariable = 0。我做错了什么?

修改 试过这样做:

global globalsource = str(username) + "@" + str(url)

然而,我收到此错误:

SyntaxError at /upload_file/
invalid syntax (views.py, line 17)
Request Method: GET
Request URL:    http://127.0.0.1:8000/upload_file/
Django Version: 1.4.1
Exception Type: SyntaxError
Exception Value:    
invalid syntax (views.py, line 17)

2 个答案:

答案 0 :(得分:4)

这是从根本上错误的做法。你应该这样做。

所有请求都可以访问全局变量。这意味着完全不相关的用户将看到该变量的先前请求的值。鉴于您使用它来访问用户的数据,这是一个严重的安全风险。

您应该在会话中存储这样的元素。

答案 1 :(得分:1)

如果在函数中的任何位置分配变量,Python会将该变量视为本地变量。所以在upload_file中你没有进入全局globalsource,而是创建一个新的本地文件,在函数结束时被抛弃。

要使Python使用全局变量,即使在分配它时,也要在global globalsource函数中添加upload_file语句。

编辑:这不是您使用global语句的方式。您需要在函数中执行此操作:

global globalsource
globalsource = str(username) + "@" + str(url)