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

2024-10-02 08:15:27 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的视图.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_文件中的全局变量值未被获取,但globalvariable=0在sync视图中被获取。我做错什么了?在

编辑: 试着这样做:

^{pr2}$

但是,我得到一个错误:

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)

Tags: thetoform视图responserequestusernamepassword
2条回答

如果将变量赋值给函数中的任何位置,Python会将该变量视为局部变量。所以在upload_file中,您没有得到全局的globalsource,而是创建了一个新的局部函数,它在函数的末尾被丢弃。在

要使Python在分配全局变量时也能使用它,请在upload_file函数中放入global globalsource语句。在

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

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

这是一个根本上错误的方法。你应该这样做。在

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

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

相关问题 更多 >

    热门问题