-
Notifications
You must be signed in to change notification settings - Fork 0
/
ftp_async.py
58 lines (50 loc) · 1.93 KB
/
ftp_async.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import asyncio
from dotenv import load_dotenv
import os
import logging
from ftplib import FTP, all_errors
import shutil
class AsyncFtpClient:
def __init__(self, host, port, username, password, timeout=10):
self.logger = logging.getLogger(__name__)
self.host = host
self.port = port
self.user = username
self.password = password
self.timeout = timeout
self.ftp = None
async def connect(self):
try:
client_ftp = FTP()
client_ftp.debugging = 5
client_ftp.connect(host=self.host, port=self.port)
client_ftp.login(user=self.user, passwd=self.password)
self.ftp = client_ftp
except all_errors as e:
logging.error(f"Error connecting to -> {self.host} \n{e}")
async def disconnect(self):
self.ftp.close()
async def sendFile(self, remotePath, localFile):
try:
fileName = os.path.basename(localFile)
logging.info("sending:" + localFile)
if os.path.exists(localFile):
with open(localFile, "rb") as file:
# file = open(localFile, 'rb')
self.ftp.cwd(remotePath)
self.ftp.storbinary("STOR " + fileName, file)
file.close()
else:
logging.error("ftp sendFile: file not found")
except all_errors as e:
logging.error(f"Error in sendFile -> {self.host} \n{e}")
async def retrieveFile(self, remotePath, localFile):
try:
fileName = os.path.basename(localFile)
logging.info("retrieving:" + localFile)
with open(localFile, "wb") as file:
self.ftp.cwd(remotePath)
self.ftp.retrbinary("RETR " + fileName, file.write, 1024)
file.close()
except all_errors as e:
logging.error(f"Error in retrieveFile -> {self.host} \n{e}")