I have written two functions- first one is to read files from SFTP and second one is to read files from Dropbox.
Both functions have some similar line of code like validating extension and reading/saving file that can be extracted into a separated function and thus need your suggestion how to do it.
PFB my both functions-
class SftpHelper:
def fetch_file_from_sftp(self, file_name, sheet_name=0):
valid_extensions = ['csv', 'xls', 'xlsx']
extension = file_name.split('.')[-1]
sftp, transport = self.connect_to_sftp()
remote_path = self.remote_dir + file_name
data = io.BytesIO()
sftp.getfo(remote_path, data, callback=None)
if extension == 'csv':
file_df = pd.read_csv(io.BytesIO(data.getvalue()))
else:
file_df = pd.read_excel(io.BytesIO(data.getvalue()), sheet_name=sheet_name)
self.close_sftp_connection(sftp, transport)
return file_df
class DropBoxHelper:
def read_file_from_dropbox(self, file_name, sheet_name=0):
valid_extensions = ['csv', 'xls', 'xlsx']
extension = file_name.split('.')[-1]
dbx = self.connect_to_dropbox()
metadata,data=dbx.files_download(file_name)
if extension == 'csv':
file_df = pd.read_csv(io.BytesIO(data.content))
else:
file_df = pd.read_excel((io.BytesIO(data.content)), sheet_name=sheet_name)
return file_df
Can anyone please help me to extract the common logix to a seperate function and then use that one in my two functions?
connect_to_sftp
andconnect_to_dropbox
methods) so that we can give you proper advice. \$\endgroup\$