File: file_usage.py

package info (click to toggle)
python-azure-storage 20181109%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 76,472 kB
  • sloc: python: 28,724; makefile: 204; sh: 1
file content (384 lines) | stat: -rw-r--r-- 15,759 bytes parent folder | download
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# 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.
# --------------------------------------------------------------------------
import io
import os
import random
import time
import uuid

from azure.storage.file import (
    ContentSettings,
)


class FileSamples():
    def __init__(self, account):
        self.account = account

    def run_all_samples(self):
        self.service = self.account.create_file_service()

        self.create_file()
        self.delete_file()
        self.file_metadata()
        self.file_properties()
        self.file_exists()
        self.resize_file()
        self.copy_file()
        self.file_range()

        self.file_with_bytes()
        self.file_with_stream()
        self.file_with_path()
        self.file_with_text()

    def _get_resource_reference(self, prefix):
        return '{}{}'.format(prefix, str(uuid.uuid4()).replace('-', ''))

    def _get_file_reference(self, prefix='file'):
        return self._get_resource_reference(prefix)

    def _create_share(self, prefix='share'):
        share_name = self._get_resource_reference(prefix)
        self.service.create_share(share_name)
        return share_name

    def _create_directory(self, share_name, prefix='dir'):
        dir_name = self._get_resource_reference(prefix)
        self.service.create_directory(share_name, dir_name)
        return dir_name

    def _get_random_bytes(self, size):
        rand = random.Random()
        result = bytearray(size)
        for i in range(size):
            result[i] = rand.randint(0, 255)
        return bytes(result)

    def create_file(self):
        share_name = self._create_share()
        directory_name = self._create_directory(share_name)

        # Basic
        file_name1 = self._get_file_reference()
        self.service.create_file(share_name, directory_name, file_name1, 512)

        # Properties
        settings = ContentSettings(content_type='html', content_language='fr')
        file_name2 = self._get_file_reference()
        self.service.create_file(share_name, directory_name, file_name2, 512, content_settings=settings)

        # Metadata
        metadata = {'val1': 'foo', 'val2': 'blah'}
        file_name2 = self._get_file_reference()
        self.service.create_file(share_name, directory_name, file_name2, 512, metadata=metadata)

        self.service.delete_share(share_name)

    def delete_file(self):
        share_name = self._create_share()
        directory_name = self._create_directory(share_name)
        file_name = self._get_file_reference()
        self.service.create_file(share_name, directory_name, file_name, 512)

        # Basic
        self.service.delete_file(share_name, directory_name, file_name)

        self.service.delete_share(share_name)

    def file_metadata(self):
        share_name = self._create_share()
        directory_name = self._create_directory(share_name)
        file_name = self._get_file_reference()
        self.service.create_file(share_name, directory_name, file_name, 512)
        metadata = {'val1': 'foo', 'val2': 'blah'}

        # Basic
        self.service.set_file_metadata(share_name, directory_name, file_name, metadata=metadata)
        metadata = self.service.get_file_metadata(share_name, directory_name,
                                                  file_name)  # metadata={'val1': 'foo', 'val2': 'blah'}

        # Replaces values, does not merge
        metadata = {'new': 'val'}
        self.service.set_file_metadata(share_name, directory_name, file_name, metadata=metadata)
        metadata = self.service.get_file_metadata(share_name, directory_name, file_name)  # metadata={'new': 'val'}

        # Capital letters
        metadata = {'NEW': 'VAL'}
        self.service.set_file_metadata(share_name, directory_name, file_name, metadata=metadata)
        metadata = self.service.get_file_metadata(share_name, directory_name, file_name)  # metadata={'new': 'VAL'}

        # Clearing
        self.service.set_file_metadata(share_name, directory_name, file_name)
        metadata = self.service.get_file_metadata(share_name, directory_name, file_name)  # metadata={}

        self.service.delete_share(share_name)

    def file_properties(self):
        share_name = self._create_share()
        directory_name = self._create_directory(share_name)
        file_name = self._get_file_reference()

        metadata = {'val1': 'foo', 'val2': 'blah'}
        self.service.create_file(share_name, directory_name, file_name, 512, metadata=metadata)

        settings = ContentSettings(content_type='html', content_language='fr')

        # Basic
        self.service.set_file_properties(share_name, directory_name, file_name, content_settings=settings)
        file = self.service.get_file_properties(share_name, directory_name, file_name)
        content_language = file.properties.content_settings.content_language  # fr
        content_type = file.properties.content_settings.content_type  # html
        content_length = file.properties.content_length  # 512

        # Metadata
        # Can't set metadata, but get will return metadata already on the file
        file = self.service.get_file_properties(share_name, directory_name, file_name)
        metadata = file.metadata  # metadata={'val1': 'foo', 'val2': 'blah'}

        # Replaces values, does not merge
        settings = ContentSettings(content_encoding='utf-8')
        self.service.set_file_properties(share_name, directory_name, file_name, content_settings=settings)
        file = self.service.get_file_properties(share_name, directory_name, file_name)
        content_encoding = file.properties.content_settings.content_encoding  # utf-8
        content_language = file.properties.content_settings.content_language  # None

        self.service.delete_share(share_name)

    def file_exists(self):
        share_name = self._create_share()
        directory_name = self._create_directory(share_name)
        file_name = self._get_file_reference()

        # Basic
        exists = self.service.exists(share_name, directory_name, file_name)  # False
        self.service.create_file(share_name, directory_name, file_name, 512)
        exists = self.service.exists(share_name, directory_name, file_name)  # True

        self.service.delete_share(share_name)

    def resize_file(self):
        share_name = self._create_share()
        directory_name = self._create_directory(share_name)
        file_name = self._get_file_reference()

        # Basic
        self.service.create_file(share_name, directory_name, file_name, 512)
        self.service.resize_file(share_name, directory_name, file_name, 1024)
        file = self.service.get_file_properties(share_name, directory_name, file_name)
        length = file.properties.content_length  # 1024

        self.service.delete_share(share_name)

    def copy_file(self):
        share_name = self._create_share()
        directory_name = self._create_directory(share_name)
        source_file_name = self._get_file_reference()
        self.service.create_file(share_name, directory_name, source_file_name, 512)

        # Basic
        # Copy the file from the directory to the root of the share
        source = self.service.make_file_url(share_name, directory_name, source_file_name)
        copy = self.service.copy_file(share_name, None, 'file1copy', source)

        # Poll for copy completion
        while copy.status != 'success':
            count = count + 1
            if count > 5:
                print('Timed out waiting for async copy to complete.')
            time.sleep(30)
            copy = self.service.get_file_properties(share_name, dir_name, 'file1copy').properties.copy

        # With SAS from a remote account to local file
        # Commented out as remote share, directory, file, and sas would need to be created
        '''
        source_file_url = self.service.make_file_url(
            remote_share_name,
            remote_directory_name,
            remote_file_name,
            sas_token=remote_sas_token,
        )
        copy = self.service.copy_file(destination_sharename, 
                                 destination_directory_name, 
                                 destination_file_name, 
                                 source_file_url)
        '''

        # Abort copy
        # Commented out as this involves timing the abort to be sent while the copy is still running
        # Abort copy is useful to do along with polling
        # self.service.abort_copy_file(share_name, dir_name, file_name, copy.id)

        self.service.delete_share(share_name)

    def file_with_bytes(self):
        share_name = self._create_share()
        directory_name = self._create_directory(share_name)

        # Basic
        data = self._get_random_bytes(15)
        file_name = self._get_file_reference()
        self.service.create_file_from_bytes(share_name, directory_name, file_name, data)
        file = self.service.get_file_to_bytes(share_name, directory_name, file_name)
        content = file.content  # data

        # Download range
        file = self.service.get_file_to_bytes(share_name, directory_name, file_name,
                                              start_range=3, end_range=10)
        content = file.content  # data from 3-10

        # Upload from index in byte array
        file_name = self._get_file_reference()
        self.service.create_file_from_bytes(share_name, directory_name, file_name, data, index=3)

        # Content settings, metadata
        settings = ContentSettings(content_type='html', content_language='fr')
        metadata = {'val1': 'foo', 'val2': 'blah'}
        file_name = self._get_file_reference()
        self.service.create_file_from_bytes(share_name, directory_name, file_name, data,
                                            content_settings=settings,
                                            metadata=metadata)
        file = self.service.get_file_to_bytes(share_name, directory_name, file_name)
        metadata = file.metadata  # metadata={'val1': 'foo', 'val2': 'blah'}
        content_language = file.properties.content_settings.content_language  # fr
        content_type = file.properties.content_settings.content_type  # html

        # Progress
        # Use slightly larger data so the chunking is more visible
        data = self._get_random_bytes(8 * 1024 * 1024)

        def upload_callback(current, total):
            print('({}, {})'.format(current, total))

        def download_callback(current, total):
            print('({}, {}) '.format(current, total))

        file_name = self._get_file_reference()

        print('upload: ')
        self.service.create_file_from_bytes(share_name, directory_name, file_name, data,
                                            progress_callback=upload_callback)

        print('download: ')
        file = self.service.get_file_to_bytes(share_name, directory_name, file_name,
                                              progress_callback=download_callback)

        self.service.delete_share(share_name)

    def file_with_stream(self):
        share_name = self._create_share()
        directory_name = self._create_directory(share_name)

        # Basic
        input_stream = io.BytesIO(self._get_random_bytes(15))
        output_stream = io.BytesIO()
        file_name = self._get_file_reference()
        self.service.create_file_from_stream(share_name, directory_name, file_name,
                                             input_stream, 15)
        file = self.service.get_file_to_stream(share_name, directory_name, file_name,
                                               output_stream)
        content_length = file.properties.content_length

        # Download range
        # Content settings, metadata
        # Progress
        # Parallelism
        # See file_with_bytes for these examples. The code will be very similar.

        self.service.delete_share(share_name)

    def file_with_path(self):
        share_name = self._create_share()
        directory_name = self._create_directory(share_name)
        INPUT_FILE_PATH = 'file_input.temp.dat'
        OUTPUT_FILE_PATH = 'file_output.temp.dat'

        data = self._get_random_bytes(4 * 1024)
        with open(INPUT_FILE_PATH, 'wb') as stream:
            stream.write(data)

        # Basic
        file_name = self._get_file_reference()
        self.service.create_file_from_path(share_name, directory_name, file_name, INPUT_FILE_PATH)
        file = self.service.get_file_to_path(share_name, directory_name, file_name, OUTPUT_FILE_PATH)
        content_length = file.properties.content_length

        # Open mode
        # Append to the file instead of starting from the beginning
        # Append streams are not seekable and so must be downloaded serially by setting max_connections=1.
        file = self.service.get_file_to_path(share_name, directory_name, file_name, OUTPUT_FILE_PATH, open_mode='ab',
                                             max_connections=1)
        content_length = file.properties.content_length  # will be the same, but local file length will be longer

        # Download range
        # Content settings, metadata
        # Progress
        # Parallelism
        # See file_with_bytes for these examples. The code will be very similar.

        self.service.delete_share(share_name)

        if os.path.isfile(INPUT_FILE_PATH):
            try:
                os.remove(INPUT_FILE_PATH)
            except:
                pass

        if os.path.isfile(OUTPUT_FILE_PATH):
            try:
                os.remove(OUTPUT_FILE_PATH)
            except:
                pass

    def file_with_text(self):
        share_name = self._create_share()
        directory_name = self._create_directory(share_name)

        # Basic
        data = u'hello world'
        file_name = self._get_file_reference()
        self.service.create_file_from_text(share_name, directory_name, file_name, data)
        file = self.service.get_file_to_text(share_name, directory_name, file_name)
        content = file.content  # 'hello world'

        # Encoding
        text = u'hello 啊齄丂狛狜 world'
        data = text.encode('utf-16')
        file_name = self._get_file_reference()
        self.service.create_file_from_text(share_name, directory_name, file_name, text, 'utf-16')
        file = self.service.get_file_to_text(share_name, directory_name, file_name, 'utf-16')
        content = file.content  # 'hello 啊齄丂狛狜 world'

        # Download range
        # Content settings, metadata
        # Progress
        # Parallelism
        # See file_with_bytes for these examples. The code will be very similar.

        self.service.delete_share(share_name)

    def file_range(self):
        share_name = self._create_share()
        directory_name = self._create_directory(share_name)
        file_name = self._get_file_reference()
        self.service.create_file(share_name, directory_name, file_name, 2048)

        # Update the file between offset 512 and 15351535
        data = b'abcdefghijklmnop' * 64
        self.service.update_range(share_name, directory_name, file_name, data, 512, 1535)

        # List ranges
        print('list ranges: ')
        ranges = self.service.list_ranges(share_name, directory_name, file_name)
        for range in ranges:
            print('({}, {}) '.format(range.start, range.end))  # (512, 1535)

        # Clear part of that range
        self.service.clear_range(share_name, directory_name, file_name, 600, 800)

        self.service.delete_share(share_name)