1

これが私の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)
4

2 に答える 2

4

これは根本的に間違ったアプローチです。これを行うべきではありません。

グローバル変数は、すべてのリクエストからアクセスできます。つまり、まったく関係のないユーザーには、その変数に対する以前のリクエストの値が表示されます。これを使用してユーザーのデータにアクセスしていることを考えると、これは重大なセキュリティ リスクです。

このような要素をセッションに保存する必要があります。

于 2012-11-16T09:03:57.427 に答える
1

関数内の任意の場所で変数に代入すると、Python はその変数をローカルとして扱います。したがって、upload_fileあなたはグローバルglobalsourceに到達していませんが、関数の最後に捨てられる新しいローカルのものを作成しています.

グローバル変数に代入しているときでも Python がグローバル変数を使用するようにするには、関数にglobal globalsourceステートメントを挿入しますupload_file

編集:それはglobalステートメントの使用方法ではありません。関数でこれを行う必要があります。

global globalsource
globalsource = str(username) + "@" + str(url)
于 2012-11-16T06:35:45.453 に答える