简体   繁体   English

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

[英]Global variable not working in Python/Django?

Here's my views.py: 这是我的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))

The problem is in sync() view. 问题出在sync()视图中。 The global variable value from upload_file is not taken but the globalvariable=0 is taken in sync view. 在同步视图中,不会使用来自upload_file的全局变量值,但会使用globalvariable = 0。 What am I doing wrong? 我究竟做错了什么?

Edit: Tried doing like this: 编辑:尝试这样做:

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

However, I get this error: 但是,我收到此错误:

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)

This is a fundamentally mistaken approach. 这是一个根本上错误的方法。 You should not do this. 您不应该这样做。

The global variable will be accessible by all requests. 全局变量将被所有请求访问。 That means a completely unrelated user will see the previous request's value for that variable. 这意味着完全不相关的用户将看到该变量的先前请求的值。 Given that you're using this to access a user's data, this is a serious security risk. 鉴于您正在使用它来访问用户的数据,因此存在严重的安全风险。

You should store elements like this in the session. 您应该在会话中存储这样的元素。

If you assign to a variable anywhere in a function, Python treats that variable as local. 如果您在函数中的任何位置分配变量,Python会将其视为本地变量。 So in upload_file you are not getting at the global globalsource , but are creating a new local one that gets thrown away at the end of the function. 因此,在upload_file您并没有获得global globalsource ,而是在函数的末尾创建了一个新的本地源。

To make Python use a global variable even when you are assigning to it, put a global globalsource statement in your upload_file function. 要使Python即使在分配时也使用全局变量,请在您的upload_file函数中放置一个global globalsource语句。

Edit: That's not how you use the global statement. 编辑:那不是您使用global语句的方式。 You need to do this in your function: 您需要在函数中执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM