1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
|
# coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
'''
FILE: blob_samples_directory_interface.py
DESCRIPTION:
This example shows how to perform common filesystem-like operations on a
container. This includes uploading and downloading files to and from the
container with an optional prefix, listing files in the container both at
a single level and recursively, and deleting files in the container either
individually or recursively.
To run this sample, provide the name of the storage container to operate on
as the script argument (e.g. `python3 directory_interface.py my-container`).
This sample expects that the `STORAGE_CONNECTION_STRING` environment
variable is set. It SHOULD NOT be hardcoded in any code derived from this
sample.
USAGE: python blob_samples_directory_interface.py CONTAINER_NAME
Set the environment variables with your own values before running the sample:
1) STORAGE_CONNECTION_STRING - the connection string to your storage account
'''
import os
from azure.storage.blob import BlobServiceClient, ContainerClient
from azure.core.exceptions import ResourceExistsError
class DirectoryClient:
def __init__(self, connection_string, container_name):
service_client = BlobServiceClient.from_connection_string(connection_string)
self.client = service_client.get_container_client(container_name)
def upload(self, source, dest):
'''
Upload a file or directory to a path inside the container
'''
if (os.path.isdir(source)):
self.upload_dir(source, dest)
else:
self.upload_file(source, dest)
def upload_file(self, source, dest):
'''
Upload a single file to a path inside the container
'''
print(f'Uploading {source} to {dest}')
with open(source, 'rb') as data:
self.client.upload_blob(name=dest, data=data)
def upload_dir(self, source, dest):
'''
Upload a directory to a path inside the container
'''
prefix = '' if dest == '' else dest + '/'
prefix += os.path.basename(source) + '/'
for root, dirs, files in os.walk(source):
for name in files:
dir_part = os.path.relpath(root, source)
dir_part = '' if dir_part == '.' else dir_part + '/'
file_path = os.path.join(root, name)
blob_path = prefix + dir_part + name
self.upload_file(file_path, blob_path)
def download(self, source, dest):
'''
Download a file or directory to a path on the local filesystem
'''
if not dest:
raise Exception('A destination must be provided')
blobs = self.ls_files(source, recursive=True)
if blobs:
# if source is a directory, dest must also be a directory
if not source == '' and not source.endswith('/'):
source += '/'
if not dest.endswith('/'):
dest += '/'
# append the directory name from source to the destination
dest += os.path.basename(os.path.normpath(source)) + '/'
blobs = [source + blob for blob in blobs]
for blob in blobs:
blob_dest = dest + os.path.relpath(blob, source)
self.download_file(blob, blob_dest)
else:
self.download_file(source, dest)
def download_file(self, source, dest):
'''
Download a single file to a path on the local filesystem
'''
# dest is a directory if ending with '/' or '.', otherwise it's a file
if dest.endswith('.'):
dest += '/'
blob_dest = dest + os.path.basename(source) if dest.endswith('/') else dest
print(f'Downloading {source} to {blob_dest}')
os.makedirs(os.path.dirname(blob_dest), exist_ok=True)
bc = self.client.get_blob_client(blob=source)
if not dest.endswith('/'):
with open(blob_dest, 'wb') as file:
data = bc.download_blob()
file.write(data.readall())
def ls_files(self, path, recursive=False):
'''
List files under a path, optionally recursively
'''
if not path == '' and not path.endswith('/'):
path += '/'
blob_iter = self.client.list_blobs(name_starts_with=path)
files = []
for blob in blob_iter:
relative_path = os.path.relpath(blob.name, path)
if recursive or not '/' in relative_path:
files.append(relative_path)
return files
def ls_dirs(self, path, recursive=False):
'''
List directories under a path, optionally recursively
'''
if not path == '' and not path.endswith('/'):
path += '/'
blob_iter = self.client.list_blobs(name_starts_with=path)
dirs = []
for blob in blob_iter:
relative_dir = os.path.dirname(os.path.relpath(blob.name, path))
if relative_dir and (recursive or not '/' in relative_dir) and not relative_dir in dirs:
dirs.append(relative_dir)
return dirs
def rm(self, path, recursive=False):
'''
Remove a single file, or remove a path recursively
'''
if recursive:
self.rmdir(path)
else:
print(f'Deleting {path}')
self.client.delete_blob(path)
def rmdir(self, path):
'''
Remove a directory and its contents recursively
'''
blobs = self.ls_files(path, recursive=True)
if not blobs:
return
if not path == '' and not path.endswith('/'):
path += '/'
blobs = [path + blob for blob in blobs]
print(f'Deleting {", ".join(blobs)}')
self.client.delete_blobs(*blobs)
# Sample setup
import sys
try:
CONNECTION_STRING = os.environ['STORAGE_CONNECTION_STRING']
except KeyError:
print('STORAGE_CONNECTION_STRING must be set')
sys.exit(1)
CONTAINER_NAME = "mycontainerdirectory2"
container = ContainerClient.from_connection_string(CONNECTION_STRING, CONTAINER_NAME)
try:
container.create_container()
except ResourceExistsError:
print("The specified container already exists.")
SAMPLE_DIRS = [
'cats/calico',
'cats/siamese',
'cats/tabby'
]
SAMPLE_FILES = [
'readme.txt',
'cats/herds.txt',
'cats/calico/anna.txt',
'cats/calico/felix.txt',
'cats/siamese/mocha.txt',
'cats/tabby/bojangles.txt'
]
for path in SAMPLE_DIRS:
os.makedirs(path, exist_ok=True)
for path in SAMPLE_FILES:
with open(path, 'w') as file:
file.write('content')
# Sample body
client = DirectoryClient(CONNECTION_STRING, CONTAINER_NAME)
# Upload a single file to the container. The destination must be a path
# including the destination file name.
#
# After this call, the container will look like:
# cat-herding/
# readme.txt
client.upload('readme.txt', 'cat-herding/readme.txt')
files = client.ls_files('', recursive=True)
print(files)
# Upload a directory to the container with a path prefix. The directory
# structure will be preserved inside the path prefix.
#
# After this call, the container will look like:
# cat-herding/
# readme.txt
# cats/
# herds.txt
# calico/
# anna.txt
# felix.txt
# siamese/
# mocha.txt
# tabby/
# bojangles.txt
client.upload('cats', 'cat-herding')
files = client.ls_files('', recursive=True)
print(files)
# List files in a single directory
# Returns:
# ['herds.txt']
files = client.ls_files('cat-herding/cats')
print(files)
# List files in a directory recursively
# Returns:
# [
# 'herds.txt',
# 'calico/anna.txt',
# 'calico/felix.txt',
# 'siamese/mocha.txt',
# 'tabby/bojangles.txt'
# ]
files = client.ls_files('cat-herding/cats', recursive=True)
print(files)
# List directories in a single directory
# Returns:
# ['calico', 'siamese', 'tabby']
dirs = client.ls_dirs('cat-herding/cats')
print(dirs)
# List files in a directory recursively
# Returns:
# ['cats', 'cats/calico', 'cats/siamese', 'cats/tabby']
dirs = client.ls_dirs('cat-herding', recursive=True)
print(dirs)
# Download a single file to a location on disk, specifying the destination file
# name. When the destination does not end with a slash '/' and is not a relative
# path specifier (e.g. '.', '..', '../..', etc), the destination will be
# interpreted as a full path including the file name. If intermediate
# directories in the destination do not exist they will be created.
#
# After this call, your working directory will look like:
# downloads/
# cat-info.txt
client.download('cat-herding/readme.txt', 'downloads/cat-info.txt')
import glob
print(glob.glob('downloads/**', recursive=True))
# Download a single file to a folder on disk, preserving the original file name.
# When the destination ends with a slash '/' or is a relative path specifier
# (e.g. '.', '..', '../..', etc), the destination will be interpreted as a
# directory name and the specified file will be saved within the destination
# directory. If intermediate directories in the destination do not exist they
# will be created.
#
# After this call, your working directory will look like:
# downloads/
# cat-info.txt
# herd-info/
# herds.txt
client.download('cat-herding/cats/herds.txt', 'downloads/herd-info/')
print(glob.glob('downloads/**', recursive=True))
# Download a directory to a folder on disk. The destination is always
# interpreted as a directory name. The directory structure will be preserved
# inside destination folder. If intermediate directories in the destination do
# not exist they will be created.
#
# After this call, your working directory will look like:
# downloads/
# cat-data/
# cats/
# herds.txt
# calico/
# anna.txt
# felix.txt
# siamese/
# mocha.txt
# tabby/
# bojangles.txt
# cat-info.txt
# herd-info/
# herds.txt
client.download('cat-herding/cats', 'downloads/cat-data')
print(glob.glob('downloads/**', recursive=True))
# Delete a single file from the container
#
# After this call, the container will look like:
# cat-herding/
# readme.txt
# cats/
# herds.txt
# calico/
# anna.txt
# siamese/
# mocha.txt
# tabby/
# bojangles.txt
client.rm('cat-herding/cats/calico/felix.txt')
files = client.ls_files('', recursive=True)
print(files)
# Delete files in a directory recursively. This is equivalent to
# client.rmdir('cat-herding/cats')
#
# After this call, the container will look like:
# cat-herding/
# readme.txt
client.rm('cat-herding/cats', recursive=True)
files = client.ls_files('', recursive=True)
print(files)
# Delete files in a directory recursively. This is equivalent to
# client.rm('cat-herding', recursive=True)
#
# After this call, the container will be empty.
client.rmdir('cat-herding')
files = client.ls_files('', recursive=True)
print(files)
# Sample cleanup
import shutil
shutil.rmtree('downloads')
shutil.rmtree('cats')
os.remove('readme.txt')
|