scrapy / scrapy
1 7
import posixpath
2

3 7
from ftplib import error_perm, FTP
4 7
from posixpath import dirname
5

6

7 7
def ftp_makedirs_cwd(ftp, path, first_call=True):
8
    """Set the current directory of the FTP connection given in the ``ftp``
9
    argument (as a ftplib.FTP object), creating all parent directories if they
10
    don't exist. The ftplib.FTP object must be already connected and logged in.
11
    """
12 7
    try:
13 7
        ftp.cwd(path)
14 0
    except error_perm:
15 0
        ftp_makedirs_cwd(ftp, dirname(path), False)
16 0
        ftp.mkd(path)
17 7
        if first_call:
18 0
            ftp.cwd(path)
19

20

21 7
def ftp_store_file(
22
        *, path, file, host, port,
23
        username, password, use_active_mode=False, overwrite=True):
24
    """Opens a FTP connection with passed credentials,sets current directory
25
    to the directory extracted from given path, then uploads the file to server
26
    """
27 7
    with FTP() as ftp:
28 7
        ftp.connect(host, port)
29 7
        ftp.login(username, password)
30 7
        if use_active_mode:
31 7
            ftp.set_pasv(False)
32 7
        file.seek(0)
33 7
        dirname, filename = posixpath.split(path)
34 7
        ftp_makedirs_cwd(ftp, dirname)
35 7
        command = 'STOR' if overwrite else 'APPE'
36 7
        ftp.storbinary(f'{command} {filename}', file)
37 7
        file.close()

Read our documentation on viewing source code .

Loading