pythondropboxdropbox-api

Set expiration date for dropbox file link


I currently try to automate some things I do with dropbox. I use python to upload files to dropbox and send a link to the file to my clients. The catch is that the link has to expire after 30 days because of data protection laws.

My idea was to simply add an expiration date to the link, however the link still leads to the file after this date, I tried it by sending emails to myself with a link that should expire after one minute.

I have a professional plan at dropbox, that is required to create links with an expiration date.

def upload_file_to_dropbox(file_path, destination_path):
    """Uploads a file to Dropbox and returns a link that expires."""
    try:
        dbx = dropbox.Dropbox(DROPBOX_ACCESS_TOKEN)

        with open(file_path, 'rb') as file:
            response = dbx.files_upload(file.read(), destination_path, mode=WriteMode("overwrite"))

        # Set link expiration time to 30 days from now
        expiration_date = datetime.now() + timedelta(minutes=1)

        shared_link_metadata = dbx.sharing_create_shared_link(response.path_display)
        file_link = shared_link_metadata.url

        # Modify the URL to set visibility and expiration
        file_link = file_link.replace("?dl=1", "?dl=0")  # Set visibility to public
        file_link += f"&expires={expiration_date.timestamp()}"  # Set expiration date

        return file_link
    # Check for authentication and API errors
    except AuthError as e:
        print("Error authenticating Dropbox account:", e)
    except dropbox.exceptions.ApiError as e:
        print("API error occurred:", e)

Solution

  • In the code you shared, you are attempting to set the expiration for the link by adding an expires parameter on the shared link itself, however that is not a supported method for setting the expiration of a Dropbox shared link.

    To set the expiration, set the SharedLinkSettings.expires on a SharedLinkSettings object that you pass to the settings parameter of the sharing_create_shared_link_with_settings call.