コード例 #1
0
ファイル: backuper.py プロジェクト: gvozdb/YaDiskBackuper
								try_ = False
								break
					except YaDiskException as e:
						if e.code == 404 or e.code == 500:
							continue

					try_i += 1
######### <<

######### >> Чистим старые логи, удаляем папку созданную для сегодняшних бекапов
if remove_old_logs:
	subprocess.Popen( "find /var/log -type f \( -name \"*.gz\" -o -name \"*.1*\" \) -exec rm '{}' \;", stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, universal_newlines=True ).communicate()

	shutil.rmtree( path_backup_today ) # удаляем папку созданную для сегодняшних бекапов
######### <<

######### >> Удаляем старые бекапы с ЯДиска
if store_old:
	for dumps_dir in disk.ls( path_webdav ):
		if dumps_dir.get('isDir') and dumps_dir.get('path') != path_webdav:
			dir_dump = dumps_dir.get('path').split('/')[-1] if dumps_dir.get('path').split('/')[-1] != '' else dumps_dir.get('path').split('/')[-2]

			dir_dump_date = dir_dump.split('-')

			date_backup = datetime( int(dir_dump_date[0]), int(dir_dump_date[1]), int(dir_dump_date[2]) ).date()
			date_today = date.today()
			date_store_old = date_today - timedelta( days=store_old )

			if date_backup <= date_store_old:
				disk.rm( path_webdav + str(date_backup) ) # Удаляем старые папки с ЯДиска
######### <<
コード例 #2
0
class YandexDiskClass:
    def __init__(self):
        self.path_main = "TelegramBOT"
        self.disk = YaDisk(config.DISK_LOGIN, config.DISK_PASSWORD_APP)
        elements = self.disk.ls("/")
        for element in elements:
            if element['isDir'] and element['displayname'] == self.path_main:
                return
        self.disk.mkdir(self.path_main)

    def get_departments(self):
        return self.disk.ls(self.path_main)

    def get_department(self, departmentName):
        try:
            return self.disk.ls(f"{self.path_main}/{departmentName}")
        except:
            return None

    def get_staffer(self, stafferID, departmentName):
        try:
            return self.disk.ls(
                f"{self.path_main}/{departmentName}/{stafferID}")
        except:
            return None

    def get_order_staffer(self, orderID, stafferID, departmentName):
        try:
            return self.disk.ls(
                f"{self.path_main}/{departmentName}/{stafferID}/{orderID}")
        except:
            return None

    def mkdir_department(self, departmentName):
        try:
            self.disk.mkdir(f"{self.path_main}/{departmentName}")
        except:
            print(
                f"YandexDisk Error: <{departmentName}> Данный отдел уже создан"
            )

    def mkdir_staffer(self, stafferID, departmentName):
        try:
            if self.get_department(departmentName):
                self.disk.mkdir(
                    f"{self.path_main}/{departmentName}/{stafferID}")
            else:
                print(
                    f"YandexDisk Error: <{departmentName}> Данный отдел не создан"
                )
        except:
            print(
                f"YandexDisk Error: <{stafferID}> Данный сотрудник уже добавлен в <{departmentName}>"
            )

    def mkdir_order(self, orderID, stafferID, departmentName):
        try:
            if self.get_staffer(stafferID, departmentName):
                self.disk.mkdir(
                    f"{self.path_main}/{departmentName}/{stafferID}/{orderID}")
            else:
                print(
                    f"YandexDisk Error: В <{departmentName}> этом отделе нет сотрудника <{stafferID}>"
                )
        except:
            print(
                f"YandexDisk Error: <{orderID}> Данный заказ уже добавлен сотруднику <{stafferID}> отдела <{departmentName}>"
            )

    def rename_department(self, departmentNameOld, departmentNameNew):
        try:
            self.disk.mkdir(f"/{self.path_main}/{departmentNameNew}/")
        except:
            print(
                f"YandexDisk Error: <{departmentNameNew}> Данный отдел уже создан"
            )
            return
        self.disk.cp(f"/{self.path_main}/{departmentNameOld}/",
                     f"/{self.path_main}/{departmentNameNew}/")
        time.sleep(2)
        self.disk.rm(f"{self.path_main}/{departmentNameOld}")

    def add_file(self, stafferID, departmentName, orderID, file):
        if not self.get_department(departmentName):
            self.mkdir_department(departmentName)
        if not self.get_staffer(stafferID, departmentName):
            self.mkdir_staffer(stafferID, departmentName)
        if not self.get_order_staffer(orderID, stafferID, departmentName):
            self.mkdir_order(orderID, stafferID, departmentName)
        elements_path = file.split('/')
        file_name = elements_path[len(elements_path) - 1]
        self.disk.upload(
            file,
            f"/{self.path_main}/{departmentName}/{stafferID}/{orderID}/{file_name}"
        )
コード例 #3
0
BASE = args.base_dir
print(f'BASE DIR: "{BASE}"')

disk = YaDisk(args.login, args.password)
exe_file = None
for f in glob.glob(BASE + '\*.exe'):
    exe_file = f

if exe_file:
    deployed_exes = [
        x['path'] for x in disk.ls(YaDiskDir) if x['path'][-4:] == '.exe'
    ]
    src = os.path.realpath(exe_file)
    dst = YaDiskDir + '/' + os.path.basename(exe_file)
    disk.upload(src, dst)
    try:
        public_url = disk.publish(dst)
        resp = requests.post(
            URL,
            dict(token=args.secret,
                 version=args.soft_version,
                 download_link=public_url))
        assert resp.json()['success'] is True
    except:
        disk.rm(dst)
    else:
        for f in deployed_exes:
            disk.rm(f)
else:
    raise EnvironmentError('Exe file list is EMPTY!!!')
コード例 #4
0
ファイル: backuper.py プロジェクト: gvozdb/YaDiskBackuper
    subprocess.Popen(
        "find /var/log -type f \( -name \"*.gz\" -o -name \"*.1*\" \) -exec rm '{}' \;",
        stderr=subprocess.PIPE,
        stdout=subprocess.PIPE,
        shell=True,
        universal_newlines=True).communicate()

    shutil.rmtree(
        path_backup_today)  # удаляем папку созданную для сегодняшних бекапов
######### <<

######### >> Удаляем старые бекапы с ЯДиска
if store_old:
    for dumps_dir in disk.ls(path_webdav):
        if dumps_dir.get('isDir') and dumps_dir.get('path') != path_webdav:
            dir_dump = dumps_dir.get('path').split('/')[-1] if dumps_dir.get(
                'path').split('/')[-1] != '' else dumps_dir.get('path').split(
                    '/')[-2]

            dir_dump_date = dir_dump.split('-')

            date_backup = datetime(int(dir_dump_date[0]),
                                   int(dir_dump_date[1]),
                                   int(dir_dump_date[2])).date()
            date_today = date.today()
            date_store_old = date_today - timedelta(days=store_old)

            if date_backup <= date_store_old:
                disk.rm(path_webdav +
                        str(date_backup))  # Удаляем старые папки с ЯДиска
######### <<