Python上傳數據

可以使用處理ftp或檔傳輸協議的python模組將數據上傳到伺服器。
需要安裝模組ftplib才能實現上面功能。

pip install ftplib

1. 使用ftplib

在下面的示例中,使用FTP方法連接到伺服器,然後提供用戶憑據。接下來,我們提到檔的名稱以及在伺服器中發送和存儲檔的storbinary方法。

import ftplib

ftp = ftplib.FTP("127.0.0.1")
ftp.login("username", "mypassword")
file = open('index.html','rb')
ftp.storbinary("STOR " + file, open(file, "rb"))
file.close()
ftp.quit()

當運行上述程式時,我們觀察到該檔的副本已在伺服器中創建。

2. 使用ftpreety

ftplib相似,可以使用ftpreety安全地連接到遠程伺服器並上傳檔。可以使用ftpreety下載檔。下麵的程式相象相同。

from ftpretty import ftpretty

# Mention the host
host = "127.0.0.1"

# Supply the credentisals
f = ftpretty(host, user, pass )

# Get a file, save it locally
f.get('someremote/file/on/server.txt', '/tmp/localcopy/server.txt')

# Put a local file to a remote location
# non-existent subdirectories will be created automatically
f.put('/tmp/localcopy/data.txt', 'someremote/file/on/server.txt')

當運行上述程式時,可以看到該檔的副本已在伺服器中創建。