You might see that the Dropbox Community team have been busy working on some major updates to the Community itself! So, here is some info on what’s changed, what’s staying the same and what you can expect from the Dropbox Community overall.

Forum Discussion

pisyavtapke's avatar
pisyavtapke
New member | Level 2
4 months ago

api

the api does not work for me to delete data on the team account, please help, does not see the folder space, just empty

import dropbox
from datetime import datetime, timedelta
import time

# Замените 'YOUR_TEAM_ACCESS_TOKEN' на ваш реальный токен доступа к командному Dropbox
ACCESS_TOKEN = ''
team_dbx = dropbox.DropboxTeam(oauth2_access_token=ACCESS_TOKEN, app_key='', app_secret='')

# Выбираем первый доступный член команды
team_member_id = team_dbx.team_members_list().members[0].profile.team_member_id
dbx = team_dbx.as_user(team_member_id)

# Функция для проверки папок и удаления файлов .raw
def delete_raw_files(folder_path=''):
try:
print('1 действие')
# Получаем список файлов и папок в папке
res = dbx.files_list_folder(folder_path)

# Флаг для проверки наличия файлов в папке
has_old_file = False

for entry in res.entries:
print('2 действие')
if isinstance(entry, dropbox.files.FileMetadata):
print(f'{entry.path_lower} {entry.client_modified} ')
# Проверяем, если файл старше 120 дней
if entry.client_modified < datetime.now() - timedelta(days=120):
has_old_file = True
elif isinstance(entry, dropbox.files.FolderMetadata):
# Рекурсивно обрабатываем вложенные папки
delete_raw_files(entry.path_lower)

# Если найдены старые файлы и папка содержит "raw" и не содержит "согласие", удаляем файлы .raw
if has_old_file and "raw" in folder_path.lower() and "согласие" not in folder_path.lower():
delete_raw_files_in_folder(folder_path)

except Exception as e:
print(f"Ошибка: {e}")

def delete_raw_files_in_folder(folder_path):
try:
print('3')
# Получаем список файлов в папке
res = dbx.files_list_folder(folder_path)

# Список форматов файлов для удаления
formats = [
'.3fr', '.ari', '.arw', '.bay', '.braw', '.crw',
'.cr2', '.cr3', '.cap', '.data', '.dcs', '.dcr',
'.dng', '.drf', '.eip', '.erf', '.fff', '.gpr',
'.iiq', '.k25', '.kdc', '.mdc', '.mef', '.mos',
'.mrw', '.nef', '.nrw', '.obm', '.orf', '.pef',
'.ptx', '.pxn', '.r3d', '.raf', '.raw', '.rwl',
'.rw2', '.rwz', '.sr2', '.srf', '.srw', '.tif',
'.x3f', '.xmp'
]

for entry in res.entries:
if isinstance(entry, dropbox.files.FileMetadata):
# Проверяем, заканчивается ли имя файла на один из форматов
if any(entry.name.lower().endswith(fmt) for fmt in formats):
# Удаляем файл
dbx.files_delete(entry.path_lower)
print(f"Удален файл: {entry.path_lower}")

except Exception as e:
print(f"Ошибка при удалении файлов в папке {folder_path}: {e}")
while True:
# Запускаем сканирование папки "Архив"
delete_raw_files()
#time.sleep(60*60*24*7)

 
  • Здравко's avatar
    Здравко
    Legendary | Level 20

    Hi pisyavtapke,

    First of all, your code is bad structured - direct use of access token is discouraged since it expires. For long term use, better use refresh token.

    Next, just pulling up arbitrary team member (even the first one - it's still unknown) is insecure if you don't relay on something "strange". Where do you know from that particular member folder is not empty yet? Did you ensure this somehow? You didn't even print the member details to check it by hands! Check all this...

    Hope this gives direction.

  • Greg-DB's avatar
    Greg-DB
    Icon for Dropbox Staff rankDropbox Staff

    In addition to what Здравко said, note that by default, API calls to the Dropbox API operate in the "member folder" of the connected account, not the "team space". That means that by default, the contents of the team space will not be found.

     

    You can configure API calls to operate in the "team space" instead though, in order to interact with files/folders in the team space. To do so, you'll need to set the "Dropbox-API-Path-Root" header. You can find information on how to use this in the Team Files Guide.

     

    Also, note that you should implement files_list_folder_continue in addition to files_list_folder

About Dropbox API Support & Feedback

Node avatar for Dropbox API Support & Feedback

Find help with the Dropbox API from other developers.

5,910 PostsLatest Activity: 4 days ago
333 Following

If you need more help you can view your support options (expected response time for an email or ticket is 24 hours), or contact us on X or Facebook.

For more info on available support options for your Dropbox plan, see this article.

If you found the answer to your question in this Community thread, please 'like' the post to say thanks and to let us know it was useful!