1
class GenericUploader(object):

    def __init__(self, data, fname):
        """data is the string we want to upload"""
        self.log = logging.getLogger(type(self).__name__)
        self.data = data
        self.data.seek(0)
        self.fname = fname

    def upload(self):
        """Should return true or false"""
        raise NotImplementedError

class SshUploader(GenericUploader):

    def __init__(self, data, fname, user, host):
        GenericUploader.__init__(self, data, fname)
        self.log.debug('Initializing SshUploader')
        self.user = user
        self.host = host

    def upload(self):
        import subprocess
        proc = subprocess.Popen(['ssh', self.user + '@' + self.host,
                                  'cat > %s' % self.fname],
                        stdin=subprocess.PIPE)
        proc.communicate(self.data.getvalue())
        if proc.returncode != 0:
            self.log.critical('Problem writing to remote server %s@%s: %d',
                              self.user, self.hos, proc.returncode)
            return False
        else:
            self.log.debug('Uploaded to ssh server %s@%s', self.user, self.host)
            return True    

class FtpUploader(GenericUploader):

        def __init__(self, data, fname, user, host, passwd):
            GenericUploader.__init__(self, data, fname)
            self.log.debug('Initializing FtpUploader')
            self.user = user
            self.host = host
            self.passwd = passwd

        def upload(self):
            import ftplib
            try:
                session = ftplib.FTP(self.host, self.user, self.passwd)
                session.storbinary('STOR %s' % self.fname, self.data)
                session.quit()
            except:
                self.log.exception('Ftp upload failed')
                return False
            else:
                self.log.debug('Uploaded to ftp server %s@%s', self.user, self.host)
                return True  

    class DropBoxUploader(GenericUploader):

            def __init__(self, data, fname, access_token):
                GenericUploader.__init__(self, data, fname)
                self.access_token = access_token

            def upload(self):
                import config
                try:
                    import dropbox
                except ImportError:
                    self.log.critical('dropbox module is required![pip install dropbox]')
                    return False
                try:
                    client = dropbox.client.DropboxClient(self.access_token)
                    # print 'linked account: ', client.account_info()
                    response = client.put_file(self.fname, self.data)
                except dropbox.rest.ErrorResponse, e:
                    self.log.exception('Exception uploading to dropbox: %s', str(e))
                    return False
                except Exception:
                    self.log.exception('Unknown exception while uploading to dropbox')
                    return False
                else:
                    self.log.debug('Uploaded to dropbox of: %s', str(client.account_info()))
                    return True

上記のコードは、SshUploader と FtpUploader に最適です。DropBoxUploader は例外をスローします。

Traceback (most recent call last):                                                                                    
2¦  File "/media/sf_aptata/ManhattanApi/insertors/uploaders.py", line 96, in upload                                     
    response = client.put_file(self.fname, self.data)                                                                 
File "/home/xubuntu/env/local/lib/python2.7/site-packages/dropbox/client.py", line 321, in put_file                 
return self.rest_client.PUT(url, file_obj, headers)                                                               
File "/home/xubuntu/env/local/lib/python2.7/site-packages/dropbox/rest.py", line 264, in PUT                        
return cls.IMPL.PUT(*n, **kw)                                                                                     
 File "/home/xubuntu/env/local/lib/python2.7/site-packages/dropbox/rest.py", line 210, in PUT                        
return self.request("PUT", url, body=body, headers=headers, raw_response=raw_response)                            
 File "/home/xubuntu/env/local/lib/python2.7/site-packages/dropbox/rest.py", line 180, in request                    
r = conn.getresponse()                                                                                            
File "/usr/lib/python2.7/httplib.py", line 1034, in getresponse                                                     
response.begin()                                                                                                  
File "/usr/lib/python2.7/httplib.py", line 407, in begin                                                            
version, status, reason = self._read_status()                                                                     
File "/usr/lib/python2.7/httplib.py", line 371, in _read_status                                                     
   raise BadStatusLine(line)                                                                                         
BadStatusLine: '' 

self.data はファイルのようなオブジェクトです ( http://docs.python.org/2/library/io.html#io.BytesIO )

テスト済み: Linux、Python 2.7.3、pip インストール ドロップボックス [https://www.dropbox.com/developers/core/sdks/python]

何か案は?

4

0 に答える 0