File: documents.py

package info (click to toggle)
azure-cosmos-python 3.1.1-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,280 kB
  • sloc: python: 11,653; makefile: 155
file content (414 lines) | stat: -rw-r--r-- 15,424 bytes parent folder | download | duplicates (2)
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#The MIT License (MIT)
#Copyright (c) 2014 Microsoft Corporation

#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:

#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.

#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.

"""AzureDocument classes and enums for the Azure Cosmos database service.
"""

import azure.cosmos.retry_options as retry_options

class DatabaseAccount(object):
    """Database account. A DatabaseAccount is the container for databases.

    :ivar str DatabaseLink:
        The self-link for Databases in the databaseAccount.
    :ivar str MediaLink:
        The self-link for Media in the databaseAccount.
    :ivar int MaxMediaStorageUsageInMB:
        Attachment content (media) storage quota in MBs (Retrieved from gateway).
    :ivar int CurrentMediaStorageUsageInMB:
        Current attachment content (media) usage in MBs (Retrieved from gateway).
        Value is returned from cached information updated periodically and
        is not guaranteed to be real time.
    :ivar dict ConsistencyPolicy:
        UserConsistencyPolicy settings.
    :ivar dict ConsistencyPolicy['defaultConsistencyLevel']:
        The default consistency level.
    :ivar int ConsistencyPolicy['maxStalenessPrefix']: 
        In bounded staleness consistency, the maximum allowed staleness in 
        terms difference in sequence numbers (aka version).
    :ivar int ConsistencyPolicy['maxStalenessIntervalInSeconds']:
        In bounded staleness consistency, the maximum allowed staleness in 
        terms time interval.
    :ivar boolean EnableMultipleWritableLocations:
        Flag on the azure Cosmos account that indicates if writes can take 
        place in multiple locations.
    """

    def __init__(self):
        self.DatabasesLink = ''
        self.MediaLink = ''
        self.MaxMediaStorageUsageInMB = 0
        self.CurrentMediaStorageUsageInMB = 0
        self.ConsumedDocumentStorageInMB = 0
        self.ReservedDocumentStorageInMB = 0
        self.ProvisionedDocumentStorageInMB = 0
        self.ConsistencyPolicy = None
        self._WritableLocations = []
        self._ReadableLocations = []
        self._EnableMultipleWritableLocations = False

    @property
    def WritableLocations(self):
        """Gets the list of writable locations for a geo-replicated database account.
        """
        return self._WritableLocations

    @property
    def ReadableLocations(self):
        """Gets the list of readable locations for a geo-replicated database account.
        """
        return self._ReadableLocations

class ConsistencyLevel(object):
    """Represents the consistency levels supported for Azure Cosmos client
    operations.

    The requested ConsistencyLevel must match or be weaker than that provisioned
    for the database account. Consistency levels.

    Consistency levels by order of strength are Strong, BoundedStaleness,
    Session, ConsistentPrefix and Eventual.

    :ivar str ConsistencyLevel.Strong:
        Strong Consistency guarantees that read operations always
        return the value that was last written.
    :ivar str ConsistencyLevel.BoundedStaleness:
        Bounded Staleness guarantees that reads are not
        too out-of-date. This can be configured based on number of operations
        (MaxStalenessPrefix) or time (MaxStalenessIntervalInSeconds).
    :ivar str ConsistencyLevel.Session:
        Session Consistency guarantees monotonic reads (you never
        read old data, then new, then old again), monotonic writes (writes
        are ordered) and read your writes (your writes are immediately
        visible to your reads) within any single session.
    :ivar str ConsistencyLevel.Eventual:
        Eventual Consistency guarantees that reads will return
        a subset of writes. All writes will be eventually be available for
        reads.
    :ivar str ConsistencyLevel.ConsistentPrefix: 
        ConsistentPrefix Consistency guarantees that
        reads will return some prefix of all writes with no gaps. All writes
        will be eventually be available for reads.
    """
    Strong = 'Strong'
    BoundedStaleness = 'BoundedStaleness'
    Session = 'Session'
    Eventual = 'Eventual'
    ConsistentPrefix = 'ConsistentPrefix'


class IndexingMode(object):
    """Specifies the supported indexing modes.

    :ivar str Consistent:
        Index is updated synchronously with a create or
        update operation. With consistent indexing, query behavior is the
        same as the default consistency level for the collection.

        The index is
        always kept up to date with the data.
    :ivar str Lazy:
        Index is updated asynchronously with respect to a create
        or update operation.

        With lazy indexing, queries are eventually consistent. The index is
        updated when the collection is idle.
    :ivar str NoIndex:
        No index is provided.

        Setting IndexingMode to "None" drops the index. Use this if you don't
        want to maintain the index for a document collection, to save the
        storage cost or improve the write throughput. Your queries will
        degenerate to scans of the entire collection.
    """
    Consistent = 'consistent'
    Lazy = 'lazy'
    NoIndex = 'none'


class IndexKind(object):
    """Specifies the index kind of index specs.

    :ivar str IndexKind.Hash:
        The index entries are hashed to serve point look up queries.
        Can be used to serve queries like: SELECT * FROM docs d WHERE d.prop = 5

    :ivar str IndexKind.Range:
        The index entries are ordered. Range indexes are optimized for
        inequality predicate queries with efficient range scans.
        Can be used to serve queries like: SELECT * FROM docs d WHERE d.prop > 5
    """
    Hash = 'Hash'
    Range = 'Range'

class PartitionKind(object):
    """Specifies the kind of partitioning to be applied.

    :ivar str PartitionKind.Hash:
        The partition key definition path is hashed.
    """
    Hash = 'Hash'

class DataType(object):
    """Specifies the data type of index specs.

    :ivar str Number:
        Represents a numeric data type.
    :ivar str String:
        Represents a string data type.
    :ivar str Point:
        Represents a point data type.
    :ivar str LineString:
        Represents a line string data type.
    :ivar str Polygon:
        Represents a polygon data type.
    :ivar str MultiPolygon:
        Represents a multi-polygon data type.
    """
    Number = 'Number'
    String = 'String'
    Point = 'Point'
    LineString = 'LineString'
    Polygon = 'Polygon'
    MultiPolygon = 'MultiPolygon'


class IndexingDirective(object):
    """Specifies whether or not the resource is to be indexed.

    :ivar int Default:
        Use any pre-defined/pre-configured defaults.
    :ivar int Exclude:
        Index the resource.
    :ivar int Include:
        Do not index the resource.
    """
    Default = 0
    Exclude = 1
    Include = 2


class ConnectionMode(object):
    """Represents the connection mode to be used by the client.

    :ivar int Gateway:
        Use the Azure Cosmos gateway to route all requests. The
        gateway proxies requests to the right data partition.
    """
    Gateway = 0


class MediaReadMode(object):
    """Represents the mode for use with downloading attachment content
    (aka media).

    :ivar str Buffered:
        Content is buffered at the client and not directly
        streamed from the content store.

        Use Buffered to reduce the time taken to read and write media files.
    :ivar str Streamed:
        Content is directly streamed from the content store
        without any buffering at the client.

        Use Streamed to reduce the client memory overhead of reading and
        writing media files.
    """
    Buffered = 'Buffered'
    Streamed = 'Streamed'


class PermissionMode(object):
    """Enumeration specifying applicability of permission.

    :ivar str PermissionMode.NoneMode:
        None.
    :ivar str PermissionMode.Read:
        Permission applicable for read operations only.
    :ivar str PermissionMode.All:
        Permission applicable for all operations.
    """
    NoneMode = 'none'  # None is python's key word.
    Read = 'read'
    All = 'all'


class TriggerType(object):
    """Specifies the type of the trigger.

    :ivar str TriggerType.Pre:
        Trigger should be executed before the associated operation(s).
    :ivar str TriggerType.Post:
        Trigger should be executed after the associated operation(s).
    """
    Pre = 'pre'
    Post = 'post'


class TriggerOperation(object):
    """Specifies the operations on which a trigger should be executed.

    :ivar str TriggerOperation.All:
        All operations.
    :ivar str TriggerOperation.Create:
        Create operations only.
    :ivar str TriggerOperation.Update:
        Update operations only.
    :ivar str TriggerOperation.Delete:
        Delete operations only.
    :ivar str TriggerOperation.Replace:
        Replace operations only.
    """
    All = 'all'
    Create = 'create'
    Update = 'update'
    Delete = 'delete'
    Replace = 'replace'


class SSLConfiguration(object):
    """Configurations for SSL connections.

    Please refer to http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification for more detail.

    :ivar str SSLKeyFIle:
        The path of the key file for ssl connection.
    :ivar str SSLCertFile:
        The path of the cert file for ssl connection.
    :ivar str SSLCaCerts:
        The path of the CA_BUNDLE file with certificates of trusted CAs.
    """
    def __init__(self):
        self.SSLKeyFile = None
        self.SSLCertFile = None
        self.SSLCaCerts = None


class ProxyConfiguration(object):
    """Configurations for proxy.

    :ivar str Host:
        The host address of the proxy.
    :ivar int Port:
        The port number of the proxy.
    """
    def __init__(self):
        self.Host = None
        self.Port = None


class ConnectionPolicy(object):
    """Represents the Connection policy assocated with a CosmosClient.

    :ivar int RequestTimeout:
        Gets or sets the request timeout (time to wait
        for response from network peer).
    :ivar int MediaRequestTimeout: 
        Gets or sets Time to wait for response
        from network peer for attachment content (aka media) operations.
    :ivar documents.ConnectionMode ConnectionMode:
        Gets or sets the connection mode used in the client. Currently 
        only Gateway is supported.
    :ivar MediaReadMode.Buffered MediaReadMode:
        Gets or sets the attachment content (aka media) download mode.
    :ivar documents.SSLConfiguration SSLConfiguration:
        Gets or sets the SSL configuration.
    :ivar documents.ProxyConfiguration ProxyConfiguration:
        Gets or sets the proxy configuration.
    :ivar boolean EnableEndpointDiscovery:
        Gets or sets endpoint discovery flag for geo-replicated database accounts.
        When EnableEndpointDiscovery is true, the client will automatically discover the
        current write and read locations and direct the requests to the correct location
        taking into consideration of the user's preference(if provided) as PreferredLocations.
    :ivar list PreferredLocations:
        Gets or sets the preferred locations for geo-replicated database accounts.
        When EnableEndpointDiscovery is true and PreferredLocations is non-empty,
        the client will use this list to evaluate the final location, taking into consideration
        the order specified in PreferredLocations list. The locations in this list are specified as the names of
        the azure Cosmos locations like, 'West US', 'East US', 'Central India' and so on.
    :ivar RetryOptions RetryOptions:
        Gets or sets the retry options to be applied to all requests when retrying.
    :ivar boolean DisableSSLVerification:
        Flag to disable SSL verification for the requests. SSL verification is enabled by default. 
        Don't set this when targeting production endpoints.
        This is intended to be used only when targeting emulator endpoint to avoid failing your requests with SSL related error.
    :ivar boolean UseMultipleWriteLocations:
        Flag to enable writes on any locations (regions) for geo-replicated database accounts in the azure Cosmos service.
    """

    __defaultRequestTimeout = 60000  # milliseconds
    # defaultMediaRequestTimeout is based upon the blob client timeout and the
    # retry policy.
    __defaultMediaRequestTimeout = 300000  # milliseconds

    def __init__(self):
        self.RequestTimeout = self.__defaultRequestTimeout
        self.MediaRequestTimeout = self.__defaultMediaRequestTimeout
        self.ConnectionMode = ConnectionMode.Gateway
        self.MediaReadMode = MediaReadMode.Buffered
        self.SSLConfiguration = None
        self.ProxyConfiguration = None
        self.EnableEndpointDiscovery = True
        self.PreferredLocations = []
        self.RetryOptions = retry_options.RetryOptions()
        self.DisableSSLVerification = False
        self.UseMultipleWriteLocations = False

class Undefined(object):
    """Represents undefined value for partitionKey when it's mising.
    """

class _OperationType(object):
    """Represents the type of the operation
    """
    Create = 'Create'
    Delete = 'Delete'
    ExecuteJavaScript = 'ExecuteJavaScript'
    Head = 'Head'
    HeadFeed = 'HeadFeed'
    Query = 'Query'
    Read = 'Read'
    ReadFeed = 'ReadFeed'
    Recreate = 'Recreate'
    Replace = 'Replace'
    SqlQuery = 'SqlQuery'
    Update = 'Update'
    Upsert = 'Upsert'

    @staticmethod
    def IsWriteOperation(operationType):
        return (operationType == _OperationType.Create or
               operationType == _OperationType.Delete or
               operationType == _OperationType.Recreate or
               operationType == _OperationType.ExecuteJavaScript or
               operationType == _OperationType.Replace or
               operationType == _OperationType.Upsert or
               operationType == _OperationType.Update)

    @staticmethod
    def IsReadOnlyOperation(operationType):
        return (operationType == _OperationType.Read or
               operationType == _OperationType.ReadFeed or
               operationType == _OperationType.Head or
               operationType == _OperationType.HeadFeed or
               operationType == _OperationType.Query or
               operationType == _OperationType.SqlQuery)