Search code examples
djangoazureasync-awaitpython-asyncioazure-file-share

How to use or work with fileshare.aio library?


I have been trying to implement the azure.storage.fileshare.aio Python SDK to upload files to my Azure File Share. I tried using the asyncio class and its functions to implement the directory_client.upload_file() function, that seems to be not working as expected.

It will be appreciated if I get some assistance, Do's and Don'ts on the same.

Thank you.


Solution

  • I created storage account in azure portal. A new file share has been added to my storage account. Check like below:

    enter image description here

    Code:

    • azure.storage.fileshare.aio package has to be installed.
    async def upload_file_to_share():
        try:
            # Initialize the ShareServiceClient asynchronously
            async with ShareServiceClient.from_connection_string(connection_string) as service_client:
                # Get a reference to the file share
                async with service_client.get_share_client(share_name) as share_client:
                    # Get a reference to the file
                    async with share_client.get_file_client(file_path) as file_client:
                        # Open the local file for reading in binary mode
                        with open(local_file_path, "rb") as local_file:
                            # Upload the file to Azure File Share asynchronously
                            await file_client.upload_file(local_file)
    
            print(f"File '{file_path}' uploaded successfully to Azure File Share.")
    
        except Exception as e:
            print(f"An error occurred: {str(e)}")
    
    async def main():
        await upload_file_to_share()
    
    
    • The above code is Executed Successfully in my environment as shown in below:

    enter image description here

    After it was done, I am able to Upload the files Successfully into my storage account as shown in below:

    Output:

    enter image description here