[英]Django - Passing variables from a function to another
我需要你的一些幫助,
我正在使用pysftp
這工作得很好,但現在我正在努力讓它在我的項目中工作在Django
在控制台工作得很好但我想從form
獲取數據所以我不需要使用console
來去做。
這是我的觀點:
def sftp_form(request):
if request.method == 'POST':
form = sftpForm(request.POST or None)
if form.is_valid():
data = form.cleaned_data
host = data['host']
usuario = data['usuario']
clave = data['clave']
print host
print usuario
print clave
else:
form=sftpForm()
return render(request, 'sftp.html', {'form':form})
def SFTP_subir():
host = raw_input('ingrese el host: ') # I want form's host here.
usuario = raw_input('ingrese el usuario: ')# I want form's usuario here.
clave = raw_input('ingrese la clave: ')# I want form's clave here.
try:
transferencia = sftp.Connection(host=host, username=usuario, password=clave)
remotepath= 'remotepath'
localpath="mylocalpath"
transferencia.put(localpath,remotepath)
print ('\n' + 'Sucess.')
except Exception, e:
print str(e)
正如你在我的代碼sftp_subir()
看到的那樣,它要求我提供主機,usuario和clave來自控制台,但我想讓它與sftp_form()
主機,usuario和clave一起使用。
這里似乎有輕微的混淆,你不能在django網絡應用程序中使用raw_input
。 如果您使用Django作為CLI ,則無法使用HTTP請求。 正如@sayse在評論中建議的那樣,如果您在Web應用程序中使用視圖,那么您需要做的就是將第二個函數定義為接受參數的函數
def sftp_form(request):
if request.method == 'POST':
form = sftpForm(request.POST or None)
if form.is_valid():
data = form.cleaned_data
host = data['host']
usuario = data['usuario']
clave = data['clave']
SFTP_subir(hosts, usuario,clave)
else:
form=sftpForm()
return render(request, 'sftp.html', {'form':form})
def SFTP_subir(hosts, usuario,clave):
try:
transferencia = sftp.Connection(host=host, username=usuario, password=clave)
remotepath= 'remotepath'
localpath="mylocalpath"
transferencia.put(localpath,remotepath)
print ('\n' + 'Sucess.')
except Exception, e:
print str(e)
一旦你創建了這段代碼,你還有很長的路要走,因為你的SFTP方法沒有返回任何有用的響應。
在你看來:
def sftp_form(request):
if request.method == 'POST':
form = sftpForm(request.POST or None)
if form.is_valid():
data = form.cleaned_data
host = data['host']
usuario = data['usuario']
clave = data['clave']
print host
print usuario
print clave
SFTP_subir(host, usuario, clave) # here you invoke the function, passing variables as arguments
else:
form=sftpForm()
return render(request, 'sftp.html', {'form':form})
然后重構你的函數來接收這些參數:
def SFTP_subir(host, usuario, clave):
try:
transferencia = sftp.Connection(host=host, username=usuario, password=clave)
remotepath= 'remotepath'
localpath="mylocalpath"
transferencia.put(localpath,remotepath)
print ('\n' + 'Sucess.')
except Exception, e:
print str(e)
你可以做到
sftp.connect(...)
...
<4 lines following>
在request.method ==“POST”塊內,而不是你的print語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.