gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:12:20 32 4
gpt4 key购买 nike

这是我的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() View 中。不采用 upload_file 中的全局变量值,但在同步 View 中采用 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)

最佳答案

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

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

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

关于python - 全局变量在 Python/Django 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13411598/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com