从blob 下载zip文件到本地并解压

def UnzipFile(req: func.HttpRequest) -> func.HttpResponse:

local_download_path="\\temp"

extract_to = "\\unzip"

req_body = req.get_json()

filePath = req_body.get("filePath")

logging.info(f'filePath:{filePath}')

创建服务客户端和文件系统客户端

service_client = get_service_client(os.getenv("CONNECTION_STRING"))

file_system_client = service_client.get_file_system_client(os.getenv("CONTAINER"))

logging.info(f'创建服务客户端和文件系统客户端 file_system_client')

try:

确保下载目录和解压目录存在

os.makedirs(os.path.join( os.getcwd(), local_download_path), exist_ok=True)

os.makedirs(os.path.join( os.getcwd(), extract_to), exist_ok=True)

except Exception as e:

logging.info(f'get local file path:{e}')

try:

下载压缩文件

local_zip_path = os.path.join( os.getcwd(), local_download_path, os.path.basename(filePath))

download_file(file_system_client, filePath, local_zip_path)

extract_to = os.path.join( os.getcwd(), extract_to)

except Exception as e:

logging.info(f'download_file failed:{e}')

logging.info(f'local_zip_path:{local_zip_path}')

logging.info(f'extract_to:{extract_to}')

解压文件

unzip_file(local_zip_path, extract_to)

data = {

'result': 'success',

'message': 'process success.',

'data': [],

'code': 200

}

将 Python 字典转换为 JSON 字符串

json_string = json.dumps(data, indent=4) # indent 参数用于格式化输出

return func.HttpResponse(

json_string,

status_code=200

)

def get_service_client(connection_string):

service_client = DataLakeServiceClient.from_connection_string(connection_string)

return service_client

def download_file(file_system_client, file_path, local_path):

try:

file_client = file_system_client.get_file_client(file_path)

download = file_client.download_file()

with open(local_path, "wb") as local_file:

local_file.write(download.readall())

print(f"Downloaded file to {local_path}")

except Exception as e:

print(e)

def unzip_file(zip_path, extract_to):

with zipfile.ZipFile(zip_path, 'r') as zip_ref:

zip_ref.extractall(extract_to)

print(f"Extracted all files to {extract_to}")

相关推荐
笨笨聊运维23 分钟前
CentOS官方不维护版本,配置python升级方法,无损版
linux·python·centos
Gerardisite26 分钟前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
小毛驴8501 小时前
软件设计模式-装饰器模式
python·设计模式·装饰器模式
jun_bai1 小时前
python写的文件备份网盘程序
运维·服务器·网络
爱吃牛肉的大老虎1 小时前
网络传输架构之gRPC讲解
网络·架构
Warren981 小时前
Python自动化测试全栈面试
服务器·网络·数据库·mysql·ubuntu·面试·职场和发展
闲人编程1 小时前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
weixin_457760001 小时前
Python 数据结构
数据结构·windows·python
欢喜躲在眉梢里2 小时前
CANN 异构计算架构实操指南:从环境部署到 AI 任务加速全流程
运维·服务器·人工智能·ai·架构·计算