簡體   English   中英

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

[英]Global variable not working in 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)

這是一個根本上錯誤的方法。 您不應該這樣做。

全局變量將被所有請求訪問。 這意味着完全不相關的用戶將看到該變量的先前請求的值。 鑒於您正在使用它來訪問用戶的數據,因此存在嚴重的安全風險。

您應該在會話中存儲這樣的元素。

如果您在函數中的任何位置分配變量,Python會將其視為本地變量。 因此,在upload_file您並沒有獲得global globalsource ,而是在函數的末尾創建了一個新的本地源。

要使Python即使在分配時也使用全局變量,請在您的upload_file函數中放置一個global globalsource語句。

編輯:那不是您使用global語句的方式。 您需要在函數中執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM