Python Network Programming 简明教程

Python - Uploading Data

我们可以使用处理 ftp 或文件传输协议的 Python 模块将数据上传到服务器。

We can upload data to a serer using python’s module which handle ftp or File Transfer Protocol.

我们需要安装模块 ftplib 才能实现此目的。

We need to install the module ftplib to acheive this.

pip install ftplib

Using ftplib

在下面的示例中,我们使用 FTP 方法连接到服务器,然后提供用户凭据。接下来,我们指定文件名称和 storbinary 方法在服务器中发送和存储文件。

In the below example we use FTP method to connect to the server and then supply the user credentials. Next we mention the name of the file and the storbinary method to send and store the file in the server.

import ftplib

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

当我们运行上面的程序时,我们观察到服务器中已创建该文件的副本。

When we run the above program, we observer that a copy of the file has been created in the server.

Using ftpreety

与 ftplib 类似,我们可以使用 ftpreety 安全地连接到远程服务器并上传文件。我们还可以使用 ftpreety 下载文件。下面的程序说明了这一点。

Similar to ftplib we can use ftpreety to connect securely to a remote server and upload file. We can aslo download file using ftpreety. The below program illustraits the same.

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')

当我们运行上面的程序时,我们观察到服务器中已创建该文件的副本。

When we run the above program, we observer that a copy of the file has been created in the server.