Hello,
I’m using the Box API with Python and the boxsdk module. I have developed a system that does the following: when a user uploads a file to a specific folder, a “FILE.UPLOADED” webhook is sent to my server. Then, my server sends a request to rename the file using the file.update_info(data={'name': 'some name'})
instruction. This works. In this case, I need to rename my files with the same name but with a suffix indicating the file number. For example: “file_1.png”, “file_2.png”, “file_3.png”…
However, when a user uploads multiple files at once, these requests happen very quickly. My system checks if a file with the same name already exists before attempting to rename the file. If it does, it tries with a higher index suffix: 1, then 2, then 3, and so on. It’s possible that my script doesn’t find a file with the same name, and then, in the time interval between the test and the request to rename the file, another file is renamed with that name. This results in a 409 status error (“Item with the same name already exists”).
To solve this problem, I made it so that every time this exception is raised, we retry renaming the file from the beginning.
Here’s my code:
def rename_file(folder_id, file_id, new_name: str):
client = box.box_client()
# Split the new name into base and extension
base, extension = os.path.splitext(new_name)
while True:
try:
# Get all file names in the current folder
items = client.folder(folder_id).get_items(limit=None, offset=0)
existing_names = [item.name for item in items if isinstance(item, boxsdk.object.file.File) and item.id != file_id]
suffix = 1
# If the new name already exists, increase the suffix
while f"{base}_{suffix}{extension}" in existing_names:
suffix += 1
name = f"{base}_{suffix}{extension}"
client.file(file_id).update_info(data={'name': name})
print(f'File {file_id} renamed "{name}" with success.')
break # if successful, break the while loop
except boxsdk.exception.BoxAPIException as e:
if e.status == 409:
print(f'File {file_id} with the same name already exists. Retrying...')
continue # retry if the name is in use
else:
raise # if the error is not due to name conflict, raise it
For some reason, when I upload 70 files at the same time, some of them are not renamed.
How can I solve this problem?
Thank you in advance for your help.
Best regards,
Antoine