I have written code in an Azure function app to setup a ShareFile client connection and write an Excel file to a File Share. The ShareFile client connection gets initialized successfully. However, when the create_file() method is called, it raises an exception '__enter__' with no further detail.
Here's the code for initializing the ShareFile client connection and writing the file using that connection:
shareClient = ShareClient(
account_url=os.environ['AZURE_STORAGE_ACCOUNT_URL'],
credential=accountKey,
share_name=shareName
)
fileClient = shareClient.get_file_client(filePath)
with fileClient.create_file(size=1024**2) as countyDispFile:
dataMartDF[export_cols].to_excel(countyDispFile, index=False)
I am trying to run the code locally in VSCode. The Python version on my machine is 3.8.17. I have also specified azure-storage-file-share in requirements.txt.
You can use below code which worked for me:
import logging as ri_lg
import os
import azure.functions as rith
from io import BytesIO
from azure.storage.fileshare import ShareClient as rith_sh_clnt
import pandas as cho
def main(req: rith.HttpRequest) -> rith.HttpResponse:
ri_lg.info('Function Started Rithwik')
rith_data = cho.DataFrame({
'test': ['test1', 'tes2t2'],
'name': ['bojja', 'rithwik']
})
ri_exp = ['test', 'name']
riffer = BytesIO()
rith_data[ri_exp].to_excel(riffer, index=False)
riffer.seek(0)
rith_acc_ky = "xAj1KqyRwaTUmijY1MyiI1ggqNBjXEVRT1mwE44A=="
file_share_nm = "rithfshare"
rith_fl_path = 'output.xlsx'
ri_sc = rith_sh_clnt(
account_url="https://rithwik81cf.file.core.windows.net",
credential=rith_acc_ky,
share_name=file_share_nm
)
ri_fc = ri_sc.get_file_client(rith_fl_path)
ri_fc.create_file(size=riffer.getbuffer().nbytes)
ri_fc.upload_file(riffer)
ri_lg.info(f"Hello Rithwik, File {rith_fl_path} uploaded to File Share in Azure.")
return rith.HttpResponse("Hello Rithwik, File Uploaded",status_code=200)
Requirements.txt:
azure-functions
azure-storage-file-share
pandas
openpyxl
Output: