CIS: ftp transfer API implemented
[living-lab-site.git] / cis / api / file_transfer.py
1 #!/usr/bin/env python
2
3 """
4 Classes that facilitate file transfer (between Web Server and CIS).
5
6 They may extend BaseFileTransferer class.
7 """
8
9 import sys
10 from ftplib import FTP_TLS
11 import base
12 import ftp_config
13 import socket
14 import api_exceptions
15 import os
16
17
18 class FTPFileTransferer(base.BaseFileTransferer):
19     """
20     FTPS implementation for file transfering between Web Server and CIS.
21     """
22
23     ftp = None
24
25     def __init__(self, local_path='', remote_path=''):
26         base.BaseFileTransferer.__init__(self, local_path, remote_path)
27
28         self.ftp = FTP_TLS(ftp_config.FTP_HOST, ftp_config.FTP_USER,
29                 ftp_config.FTP_PASSWD, ftp_config.FTP_ACCT)
30         self.ftp.set_pasv(True)
31
32     def get(self, files):
33         for crt_file in files:
34             crt_file = os.path.join(self.local_path, crt_file)
35             try:
36                 file_local = open(crt_file, 'wb')
37             except IOError as e:
38                 raise api_exceptions.FileTransferException( \
39                         "Could not open local file '%s' for writing: %s" \
40                         % (crt_file, repr(e)))
41
42             try:
43                 self.ftp.cwd(self.remote_path)
44                 self.ftp.retrbinary('RETR %s' % crt_file, file_local.write)
45                 file_local.close()
46             except ftplib.error_perm as e:
47                 raise api_exceptions.FileTransferException( \
48                         "Could not get file '%s' from Web Server: %s" \
49                         % (crt_file, repr(e)))
50
51     def put(self, files):
52         for crt_file in files:
53             crt_file = os.path.join(self.local_path, crt_file)
54
55             try:
56                 file_local = open(crt_file, 'rb')
57             except IOError as e:
58                 raise api_exceptions.FileTransferException( \
59                         "Could not open local file '%s' for reading: %s" \
60                         % (crt_file, repr(e)))
61                 
62             try:
63                 self.ftp.cwd(self.remote_path)
64                 self.ftp.storbinary('STOR %s' % crt_file, file_local)
65                 file_local.close()
66             except ftplib.error_perm as e:
67                 raise api_exceptions.FileTransferException( \
68                         "Could not get file '%s' from Web Server: %s" \
69                         % (crt_file, repr(e)))
70
71     def close(self):
72         if self.ftp is not None:
73             self.ftp.quit()