示例#1
0
def run_sample():
    with IDisposable(cosmos_client.CosmosClient(HOST, {'masterKey': MASTER_KEY} )) as client:
        try:
            # setup database for this sample
            try:
                client.CreateDatabase({"id": DATABASE_ID})

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    pass
                else:
                    raise errors.HTTPFailure(e.status_code)

            # setup collection for this sample
            try:
                client.CreateContainer(database_link, {"id": COLLECTION_ID})
                print('Collection with id \'{0}\' created'.format(COLLECTION_ID))

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    print('Collection with id \'{0}\' was found'.format(COLLECTION_ID))
                else:
                    raise errors.HTTPFailure(e.status_code)

            DocumentManagement.CreateDocuments(client)
            DocumentManagement.ReadDocument(client,'SalesOrder1')
            DocumentManagement.ReadDocuments(client)

        except errors.HTTPFailure as e:
            print('\nrun_sample has caught an error. {0}'.format(e.message))
        
        finally:
            print("\nrun_sample done")
示例#2
0
    def __init__(self, database_id, container_id):

        # Initialize the Cosmos client
        self.client = cosmos_client.CosmosClient(
            url_connection=cosmosdb_config['ENDPOINT'],
            auth={'masterKey': cosmosdb_config['PRIMARYKEY']})
        '''
        This utility will create the specified database and container 
        if they don't exist already
        '''

        # Define database link
        self.database_link = 'dbs/' + database_id
        try:
            db = self.client.ReadDatabase(self.database_link)
            logger.info('Initiated DB ->', db)

        except errors.HTTPFailure as e:
            if e.status_code == 404:
                print(
                    'The database \'{0}\' DOES NOT exist.'.format(database_id))

                self.create_database(database_id)
                db = self.client.ReadDatabase(self.database_link)
                print('[Info] Successfully created {0} -> {1}'.format(
                    database_id, db))

            else:
                raise errors.HTTPFailure(e.status_code)

        except Exception as e:
            raise e

        # Define container link
        self.container_link = self.database_link + \
            '/colls/' + container_id

        try:
            container = self.client.ReadContainer(self.container_link,
                                                  options=None)
            logger.info('Initiated Container ->', container)

        except errors.HTTPFailure as e:
            if e.status_code == 404:
                print('The container \'{0}\' DOES NOT exist.'.format(
                    container_id))

                self.create_container(container_id)
                container = self.client.ReadContainer(self.container_link,
                                                      options=None)
                print('[Info] Successfully created {0} -> {1}'.format(
                    container_id, container))

            else:
                raise errors.HTTPFailure(e.status_code)

        except Exception as e:
            raise e
示例#3
0
def main():
    '''
    h = hashing.Hash()
    k = keys.Key()
    s = signature.Signature()
    e = encrypt.Encrypt()

    a = k.generate_keys()
    b = k.generate_keys()

    alice = user.User(a['publicKey'], a['privateKey'])
    bob = user.User(b['publicKey'], b['privateKey'])
    '''

    with d.IDisposable(
            cosmos_client.CosmosClient(d.HOST,
                                       {'masterKey': d.MASTER_KEY})) as client:
        try:
            ''''''
            # setup database for this sample
            try:
                client.CreateDatabase({"id": d.DATABASE_ID})

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    pass
                else:
                    raise errors.HTTPFailure(e.status_code)

            # setup collection for this sample
            try:
                client.CreateContainer(d.database_link,
                                       {"id": d.COLLECTION_ID})
                print('Collection with id \'{0}\' created'.format(
                    d.COLLECTION_ID))

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    print('Collection with id \'{0}\' was found'.format(
                        d.COLLECTION_ID))
                else:
                    raise errors.HTTPFailure(e.status_code)

            #d.DocumentManagement.CreateDocuments(client)

            #key = d.DocumentManagement.ReadDocument(client,'9d88e4ce-3fe8-49e2-9c8f-446530299c13')
            #k = keys.Key().read_key(key)
            #print(k)

            #d.DocumentManagement.ReadDocuments(client)

        except errors.HTTPFailure as e:
            print('\nrun_sample has caught an error. {0}'.format(
                e._http_error_message))

        finally:
            print("\nrun_sample done")
示例#4
0
def run_sample():
    with IDisposable(
            cosmos_client.CosmosClient(HOST,
                                       {'masterKey': MASTER_KEY})) as client:
        try:
            # setup database for this sample
            try:
                db = client.create_database(id=DATABASE_ID)

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    pass
                else:
                    raise errors.HTTPFailure(e.status_code)

            # setup container for this sample
            try:
                container = db.create_container(id=CONTAINER_ID,
                                                partition_key=PartitionKey(
                                                    path='/id', kind='Hash'))
                print('Container with id \'{0}\' created'.format(CONTAINER_ID))

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    print('Container with id \'{0}\' was found'.format(
                        CONTAINER_ID))
                else:
                    raise errors.HTTPFailure(e.status_code)

            ItemManagement.CreateItems(container)
            ItemManagement.ReadItem(container, 'SalesOrder1')
            ItemManagement.ReadItems(container)
            ItemManagement.QueryItems(container, 'SalesOrder1')
            ItemManagement.ReplaceItem(container, 'SalesOrder1')
            ItemManagement.UpsertItem(container, 'SalesOrder1')
            ItemManagement.DeleteItem(container, 'SalesOrder1')

            # cleanup database after sample
            try:
                client.delete_database(db)

            except errors.CosmosError as e:
                if e.status_code == 404:
                    pass
                else:
                    raise errors.HTTPFailure(e.status_code)

        except errors.HTTPFailure as e:
            print('\nrun_sample has caught an error. {0}'.format(e.message))

        finally:
            print("\nrun_sample done")
示例#5
0
def main():
    print("Running receiver")
    with d.IDisposable(
            cosmos_client.CosmosClient(d.HOST,
                                       {'masterKey': d.MASTER_KEY})) as client:
        try:
            ''''''
            # setup database for this sample
            try:
                client.CreateDatabase({"id": d.DATABASE_ID})

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    pass
                else:
                    raise errors.HTTPFailure(e.status_code)

            # setup collection for this sample
            try:
                client.CreateContainer(d.database_link,
                                       {"id": d.COLLECTION_ID})
                print('Collection with id \'{0}\' created'.format(
                    d.COLLECTION_ID))

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    print('Collection with id \'{0}\' was found'.format(
                        d.COLLECTION_ID))
                else:
                    raise errors.HTTPFailure(e.status_code)

            # Create keys and queue
            # d.DocumentManagement.CreateDocuments(client)

            data = d.DocumentManagement.ReadDocument(
                client, '0376af03-9620-4980-a905-dbfa6b189495')
            publicKey = keys.Key().read_key(data['publicKey'])
            privateKey = keys.Key().read_key_from_file('wxptlpygzv')
            queue = data['queue']

            print(publicKey)
            print(privateKey)
            print(queue)

        except errors.HTTPFailure as e:
            print('\nrun_sample has caught an error. {0}'.format(
                e._http_error_message))

        finally:
            print("\nrun_sample done")
示例#6
0
def run_sample():

    with IDisposable(
            cosmos_client.CosmosClient(HOST,
                                       {'masterKey': MASTER_KEY})) as client:
        try:
            # setup database for this sample
            try:
                db = client.create_database(id=DATABASE_ID)

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    pass
                else:
                    raise errors.HTTPFailure(e.status_code)

            # query for a container
            ContainerManagement.find_container(db, CONTAINER_ID)

            # create a container
            ContainerManagement.create_Container(db, CONTAINER_ID)

            # get & change Offer Throughput of container
            ContainerManagement.manage_offer_throughput(db, CONTAINER_ID)

            # get a container using its id
            ContainerManagement.read_Container(db, CONTAINER_ID)

            # list all container on an account
            ContainerManagement.list_Containers(db)

            # delete container by id
            ContainerManagement.delete_Container(db, CONTAINER_ID)

            # cleanup database after sample
            try:
                client.delete_database(db)

            except errors.CosmosError as e:
                if e.status_code == 404:
                    pass
                else:
                    raise errors.HTTPFailure(e.status_code)

        except errors.HTTPFailure as e:
            print('\nrun_sample has caught an error. {0}'.format(e.message))

        finally:
            print("\nrun_sample done")
def run_sample():

    with IDisposable(
            cosmos_client.CosmosClient(HOST,
                                       {'masterKey': MASTER_KEY})) as client:
        try:
            # setup database for this sample
            try:
                client.CreateDatabase({"id": DATABASE_ID})

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    pass
                else:
                    raise errors.HTTPFailure(e.status_code)

            # query for a collection
            CollectionManagement.find_Container(client, COLLECTION_ID)

            # create a collection
            CollectionManagement.create_Container(client, COLLECTION_ID)

            # get & change Offer Throughput of collection
            CollectionManagement.manage_offer_throughput(client, COLLECTION_ID)

            # get a collection using its id
            CollectionManagement.read_Container(client, COLLECTION_ID)

            # list all collection on an account
            CollectionManagement.list_Containers(client)

            # delete collection by id
            CollectionManagement.delete_Container(client, COLLECTION_ID)

            # cleanup database after sample
            try:
                client.DeleteDatabase(database_link)

            except errors.CosmosError as e:
                if e.status_code == 404:
                    pass
                else:
                    raise errors.HTTPFailure(e.status_code)

        except errors.HTTPFailure as e:
            print('\nrun_sample has caught an error. {0}'.format(e.message))

        finally:
            print("\nrun_sample done")
示例#8
0
def run_sample():
    with IDisposable(
            cosmos_client.CosmosClient(HOST,
                                       {'masterKey': MASTER_KEY})) as client:
        try:
            # setup database for this sample
            try:
                client.CreateDatabase({"id": DATABASE_ID})

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    pass
                else:
                    raise errors.HTTPFailure(e.status_code)

            # setup collection for this sample

            collection_definition = {
                'id': CONTAINER_ID,
                'partitionKey': {
                    'paths': ['/address/state'],
                    'kind': documents.PartitionKind.Hash
                }
            }

            try:
                client.CreateContainer(database_link, collection_definition)
                print(
                    'Collection with id \'{0}\' created'.format(COLLECTION_ID))

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    print('Collection with id \'{0}\' was found'.format(
                        COLLECTION_ID))
                else:
                    raise errors.HTTPFailure(e.status_code)

            ChangeFeedManagement.CreateDocuments(client)
            ChangeFeedManagement.ReadFeed(client)
            time = datetime.datetime.now()
            ChangeFeedManagement.CreateDocuments(client)
            ChangeFeedManagement.ReadFeedForTime(client, time)

        except errors.HTTPFailure as e:
            print('\nrun_sample has caught an error. {0}'.format(e.message))

        finally:
            print("\nrun_sample done")
示例#9
0
def run_sample():
    with IDisposable(cosmos_client.CosmosClient(HOST, {'masterKey': MASTER_KEY})) as client:
        try:
            # setup database for this sample
            try:
                db = client.create_database(id=DATABASE_ID)

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    pass
                else:
                    raise errors.HTTPFailure(e.status_code)

            # setup container for this sample
            try:
                container, document = ItemManagement.CreateNonPartitionedCollection(db)
                print('Container with id \'{0}\' created'.format(CONTAINER_ID))

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    print('Container with id \'{0}\' was found'.format(CONTAINER_ID))
                else:
                    raise errors.HTTPFailure(e.status_code)

            # Read Item created in non partitioned collection using older API version
            ItemManagement.ReadItem(container, document['id'])
            ItemManagement.CreateItems(container)
            ItemManagement.ReadItems(container)
            ItemManagement.QueryItems(container, 'SalesOrder1')
            ItemManagement.ReplaceItem(container, 'SalesOrder1')
            ItemManagement.UpsertItem(container, 'SalesOrder1')
            ItemManagement.DeleteItem(container, 'SalesOrder1')

            # cleanup database after sample
            try:
                client.delete_database(db)

            except errors.CosmosError as e:
                if e.status_code == 404:
                    pass
                else:
                    raise errors.HTTPFailure(e.status_code)

        except errors.HTTPFailure as e:
            print('\nrun_sample has caught an error. {0}'.format(e.message))

        finally:
            print("\nrun_sample done")
 def _MockExecuteFunctionEndpointDiscover(self, function, *args, **kwargs):
     self.counter += 1
     if self.counter >= 7:
         return self.OriginalExecuteFunction(function, *args, **kwargs)
     else:
         self.endpoint_sequence.append(args[1].location_endpoint_to_route)
         raise errors.HTTPFailure(StatusCodes.FORBIDDEN, "Request is not permitted in this region", {HttpHeaders.SubStatus: SubStatusCodes.WRITE_FORBIDDEN})
示例#11
0
    def ReadDocuments(client, db, coll):
        try:
            if DatabaseManagement.find_database(
                    client, db) and CollectionManagement.find_Container(
                        client, db, coll):
                db_link = 'dbs/' + db
                collection_link = db_link + '/colls/{0}'.format(coll)
                print('\nReading all documents in a collection\n')

                # NOTE: Use MaxItemCount on Options to control how many documents come back per trip to the server
                #       Important to handle throttles whenever you are doing operations such as this that might
                #       result in a 429 (throttled request)
                documentlist = list(
                    client.ReadItems(collection_link, {'maxItemCount': 10}))

                print('Found {0} documents'.format(documentlist.__len__()))

                for doc in documentlist:
                    print('Document Id: {0}'.format(doc.get('id')))
            else:
                print("Invalid DB or Collection")
        except errors.HTTPFailure as e:
            if e.status_code == 404:
                print('A collection with id \'{0}\' does not exist'.format(id))
            else:
                raise errors.HTTPFailure(e.status_code)
示例#12
0
    def CreateDocuments(client, db, coll):
        try:
            if DatabaseManagement.find_database(
                    client, db) and CollectionManagement.find_Container(
                        client, db, coll):
                db_link = 'dbs/' + db
                collection_link = db_link + '/colls/{0}'.format(coll)
                print('Creating Documents')

                # Create a SalesOrder object. This object has nested properties and various types including numbers, DateTimes and strings.
                # This can be saved as JSON as is without converting into rows/columns.
                sales_order = DocumentManagement.GetSalesOrder("SalesOrder1")
                client.CreateItem(collection_link, sales_order)
                print("creating document salesorde2")
                # As your app evolves, let's say your object has a new schema. You can insert SalesOrderV2 objects without any
                # changes to the database tier.
                # sales_order2 = DocumentManagement.GetSalesOrderV2("SalesOrder2")
                # client.CreateItem(collection_link, sales_order2)
            else:
                print("Invalid DB or Collection")
        except errors.HTTPFailure as e:
            if e.status_code == 404:
                print('A collection with id \'{0}\' does not exist'.format(id))
            else:
                raise errors.HTTPFailure(e.status_code)
示例#13
0
    def delete_item(self, document_id):
        query = {
            'query': 'SELECT * FROM c WHERE c.id = "{0}"'.format(document_id)
        }
        try:
            results = self.client.QueryItems(self.container_link, query,
                                             self.default_options())

            for result in list(results):
                options = self.default_options()
                options['partitionKey'] = result['partitionKey']
                doc_link = self.container_link + '/docs/' + result['id']
                output = self.client.DeleteItem(doc_link, options)
                print('[Info] Successfully deleted item {}'.format(
                    result['id']))
            return output

        except errors.HTTPFailure as e:
            if e.status_code == 404:
                print('[Delete] A collection with id \'{0}\' DOES NOT exist'.
                      format(self.container_link))
            else:
                raise errors.HTTPFailure(e.status_code)
        except Exception as e:
            raise e
示例#14
0
    def manage_offer_throughput(client, id):
        print("\n3.1 Get Collection Performance tier")
        
        #A Collection's Offer Throughput determines the performance throughput of a collection. 
        #A Collection is loosely coupled to Offer through the Offer's offerResourceId
        #Offer.offerResourceId == Collection._rid
        #Offer.resource == Collection._self
        
        try:
            # read the collection, so we can get its _self
            collection_link = database_link + '/colls/{0}'.format(id)
            collection = client.ReadContainer(collection_link)

            # now use its _self to query for Offers
            offer = list(client.QueryOffers('SELECT * FROM c WHERE c.resource = \'{0}\''.format(collection['_self'])))[0]
            
            print('Found Offer \'{0}\' for Collection \'{1}\' and its throughput is \'{2}\''.format(offer['id'], collection['_self'], offer['content']['offerThroughput']))

        except errors.HTTPFailure as e:
            if e.status_code == 404:
                print('A collection with id \'{0}\' does not exist'.format(id))
            else: 
                raise errors.HTTPFailure(e.status_code)

        print("\n3.2 Change Offer Throughput of Collection")
                           
        #The Offer Throughput of a collection controls the throughput allocated to the Collection
        #To increase (or decrease) the throughput of any Collection you need to adjust the Offer.content.offerThroughput
        #of the Offer record linked to the Collection
        
        #The following code shows how you can change Collection's throughput
        offer['content']['offerThroughput'] += 100
        offer = client.ReplaceOffer(offer['_self'], offer)

        print('Replaced Offer. Offer Throughput is now \'{0}\''.format(offer['content']['offerThroughput']))
示例#15
0
    def manage_offer_throughput(db, id):
        print("\n3.1 Get Container Performance tier")

        #A Container's Offer Throughput determines the performance throughput of a container.
        #A Container is loosely coupled to Offer through the Offer's offerResourceId
        #Offer.offerResourceId == Container._rid
        #Offer.resource == Container._self

        try:
            # read the container, so we can get its _self
            container = db.get_container_client(container=id)

            # now use its _self to query for Offers
            offer = container.read_offer()

            print(
                'Found Offer \'{0}\' for Container \'{1}\' and its throughput is \'{2}\''
                .format(offer.properties['id'], container.id,
                        offer.properties['content']['offerThroughput']))

        except errors.HTTPFailure as e:
            if e.status_code == 404:
                print('A container with id \'{0}\' does not exist'.format(id))
            else:
                raise errors.HTTPFailure(e.status_code)

        print("\n3.2 Change Offer Throughput of Container")

        #The Offer Throughput of a container controls the throughput allocated to the Container

        #The following code shows how you can change Container's throughput
        offer = container.replace_throughput(offer.offer_throughput + 100)
        print('Replaced Offer. Offer Throughput is now \'{0}\''.format(
            offer.properties['content']['offerThroughput']))
    def test_retry_policy_does_not_mark_null_locations_unavailable(self):
        self.original_get_database_account = cosmos_client_connection.CosmosClientConnection.GetDatabaseAccount
        cosmos_client_connection.CosmosClientConnection.GetDatabaseAccount = self.mock_get_database_account

        client = cosmos_client_connection.CosmosClientConnection(
            self.DEFAULT_ENDPOINT, {'masterKey': self.MASTER_KEY}, None,
            documents.ConsistencyLevel.Eventual)
        endpoint_manager = global_endpoint_manager._GlobalEndpointManager(
            client)

        self.original_mark_endpoint_unavailable_for_read_function = endpoint_manager.mark_endpoint_unavailable_for_read
        endpoint_manager.mark_endpoint_unavailable_for_read = self._mock_mark_endpoint_unavailable_for_read
        self.original_mark_endpoint_unavailable_for_write_function = endpoint_manager.mark_endpoint_unavailable_for_write
        endpoint_manager.mark_endpoint_unavailable_for_write = self._mock_mark_endpoint_unavailable_for_write
        self.original_resolve_service_endpoint = endpoint_manager.resolve_service_endpoint
        endpoint_manager.resolve_service_endpoint = self._mock_resolve_service_endpoint

        # Read and write counters count the number of times the endpoint manager's
        # mark_endpoint_unavailable_for_read() and mark_endpoint_unavailable_for_read()
        # functions were called. When a 'None' location is returned by resolve_service_endpoint(),
        # these functions  should not be called
        self._read_counter = 0
        self._write_counter = 0
        request = _RequestObject(http_constants.ResourceType.Document,
                                 documents._OperationType.Read)
        endpointDiscovery_retry_policy = endpoint_discovery_retry_policy._EndpointDiscoveryRetryPolicy(
            documents.ConnectionPolicy(), endpoint_manager, request)
        endpointDiscovery_retry_policy.ShouldRetry(
            errors.HTTPFailure(http_constants.StatusCodes.FORBIDDEN))
        self.assertEqual(self._read_counter, 0)
        self.assertEqual(self._write_counter, 0)

        self._read_counter = 0
        self._write_counter = 0
        request = _RequestObject(http_constants.ResourceType.Document,
                                 documents._OperationType.Create)
        endpointDiscovery_retry_policy = endpoint_discovery_retry_policy._EndpointDiscoveryRetryPolicy(
            documents.ConnectionPolicy(), endpoint_manager, request)
        endpointDiscovery_retry_policy.ShouldRetry(
            errors.HTTPFailure(http_constants.StatusCodes.FORBIDDEN))
        self.assertEqual(self._read_counter, 0)
        self.assertEqual(self._write_counter, 0)

        endpoint_manager.mark_endpoint_unavailable_for_read = self.original_mark_endpoint_unavailable_for_read_function
        endpoint_manager.mark_endpoint_unavailable_for_write = self.original_mark_endpoint_unavailable_for_write_function
        cosmos_client_connection.CosmosClientConnection.GetDatabaseAccount = self.original_get_database_account
示例#17
0
def run_sample():
    with IDisposable(cosmos_client.CosmosClient(HOST, {'masterKey': MASTER_KEY} )) as client:
        try:
            # setup database for this sample
            try:
                db = client.create_database(id=DATABASE_ID)

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    pass
                else:
                    raise errors.HTTPFailure(e.status_code)

            # setup container for this sample
            try:
                container = db.create_container(
                    id=CONTAINER_ID,
                    partition_key=partition_key.PartitionKey(path='/address/state', kind=documents.PartitionKind.Hash)
                )
                print('Container with id \'{0}\' created'.format(CONTAINER_ID))

            except errors.HTTPFailure as e:
                if e.status_code == 409:
                    print('Container with id \'{0}\' was found'.format(CONTAINER_ID))
                else:
                    raise errors.HTTPFailure(e.status_code)

            ChangeFeedManagement.CreateItems(container, 100)
            ChangeFeedManagement.ReadChangeFeed(container)

            # cleanup database after sample
            try:
                client.delete_database(db)

            except errors.CosmosError as e:
                if e.status_code == 404:
                    pass
                else:
                    raise errors.HTTPFailure(e.status_code)

        except errors.HTTPFailure as e:
            print('\nrun_sample has caught an error. {0}'.format(e.message))
        
        finally:
            print("\nrun_sample done")
示例#18
0
def updateCosmosDB(scheduleJSON):
    try:
        client.CreateItem(connectionString, scheduleJSON)
        return True
    except errors.HTTPFailure as e:
        if e.status_code >= 400:  # Move these constants to an enum
            return False
        else:
            raise errors.HTTPFailure(e.status_code)
    def MockExecuteFunction(self, function, *args, **kwargs):
        global location_changed

        if self.endpoint_discovery_retry_count == 2:
            retry_utility._ExecuteFunction = self.OriginalExecuteFunction
            return (json.dumps([{ 'id': 'mock database' }]), None)
        else:
            self.endpoint_discovery_retry_count += 1
            location_changed = True
            raise errors.HTTPFailure(StatusCodes.FORBIDDEN, "Forbidden", {'x-ms-substatus' : 3})
示例#20
0
 def _MockExecuteFunctionEndpointDiscover(self, function, *args, **kwargs):
     self.counter += 1
     if self.counter >= 10 or (len(args) > 0 and args[1].operation_type
                               == documents._OperationType.Read):
         return ({}, {})
     else:
         self.endpoint_sequence.append(args[1].location_endpoint_to_route)
         raise errors.HTTPFailure(
             StatusCodes.FORBIDDEN,
             "Request is not permitted in this region",
             {HttpHeaders.SubStatus: SubStatusCodes.WRITE_FORBIDDEN})
示例#21
0
def CreateDatabaseIfNotExists(client, database_id):
    try:
        database = Query_Entities(client, 'database', id=database_id)
        if database == None:
            database = client.CreateDatabase({"id": database_id})
        return database
    except errors.HTTPFailure as e:
        if e.status_code == 409:  # Move these constants to an enum
            pass
        else:
            raise errors.HTTPFailure(e.status_code)
示例#22
0
 def initialize_container(self, database_id=config['DATABASE'], container_id=config['CONTAINER']):
     try:
         database_link = 'dbs/' + database_id
         container_definition = {
             'id': container_id,
             "indexingPolicy": {
                 "indexingMode": "consistent", # consistent or lazy
                 "automatic": True,
                 "includedPaths": [{
                     "path": "/*",
                     "indexes": [{
                         "kind": "Range",
                         "dataType": "Number",
                         "precision": -1
                     },{
                         "kind": "Range",
                         "dataType": "String",
                         "precision": -1
                     },{
                         "kind": "Spatial",
                         "dataType": "Point"
                     }
                 ]}],
                 "excludedPaths": [{
                     "path": "/\"_etag\"/?"
                 }]
             },
             "partitionKey": {
                 "paths": [
                   "/partitionKey"
                 ],
                 "kind": "Hash",
             },
             "uniqueKeyPolicy": {
                 "uniqueKeys": [{
                     "paths": [
                         "/partitionKey",
                         "/mailaddr",
                     ]}
                     # ,{
                     # "paths": [
                     #     "/testaddr"
                     # ]}
                 ]
             }
         }
         return self.client.CreateContainer(database_link, container_definition, {'offerThroughput': 400})
     except errors.CosmosError as e:
         if e.status_code == 409:
             logger.error('A collection with id \'{0}\' already exists'.format(self.container_link))
         else:
             raise errors.HTTPFailure(e.status_code) 
     except Exception as e:
         raise e
示例#23
0
 def initialize_database(self, database_id=config['DATABASE']):
     try:        
         return self.client.CreateDatabase({'id': database_id})
         # database_link = self.database_link
         # database_link = db['_self']
     except errors.HTTPFailure as e:
         if e.status_code == 409:
            print('A database with id \'{0}\' already exists'.format(self.database_link))
         else:
             raise errors.HTTPFailure(e.status_code)
     except Exception as e:
         raise e
示例#24
0
    def create_database(client, id):
        print("\n2. Create Database")

        try:
            client.create_database(id=id)
            print('Database with id \'{0}\' created'.format(id))

        except errors.HTTPFailure as e:
            if e.status_code == 409:
                print('A database with id \'{0}\' already exists'.format(id))
            else:
                raise errors.HTTPFailure(e.status_code)
示例#25
0
 def upsert_item(self, item):
     try:
         result = self.client.UpsertItem(self.container_link, item, self.get_options())
         logger.info(result)
         return result
     except errors.HTTPFailure as e:
         if e.status_code == 404:
             print('A collection with id \'{0}\' does not exist'.format(self.container_link))
         else:
             raise errors.HTTPFailure(e.status_code)
     except Exception as e:
         raise e
示例#26
0
    def delete_database(client, id):
        print("\n5. Delete Database")

        try:
            client.delete_database(id)

            print('Database with id \'{0}\' was deleted'.format(id))

        except errors.HTTPFailure as e:
            if e.status_code == 404:
                print('A database with id \'{0}\' does not exist'.format(id))
            else:
                raise errors.HTTPFailure(e.status_code)
示例#27
0
    def read_item(self, id):
        query = {'query': 'SELECT * FROM c WHERE c.id = "{0}"'.format(id)}

        try:
            results = list(self.client.QueryItems(self.container_link, query, self.get_options()))
            return results
        except errors.HTTPFailure as e:
            if e.status_code == 404:
                print('A collection with id \'{0}\' does not exist'.format(self.container_link))
            else:
                raise errors.HTTPFailure(e.status_code)
        except Exception as e:
            raise e
示例#28
0
    def read_Container(db, id):
        print("\n4. Get a Container by id")

        try:
            container = db.get_container_client(id)
            print('Container with id \'{0}\' was found, it\'s link is {1}'.
                  format(container.id, container.container_link))

        except errors.HTTPFailure as e:
            if e.status_code == 404:
                print('A container with id \'{0}\' does not exist'.format(id))
            else:
                raise errors.HTTPFailure(e.status_code)
示例#29
0
    def delete_Container(db, id):
        print("\n6. Delete Container")

        try:
            db.delete_container(id)

            print('Container with id \'{0}\' was deleted'.format(id))

        except errors.HTTPFailure as e:
            if e.status_code == 404:
                print('A container with id \'{0}\' does not exist'.format(id))
            else:
                raise errors.HTTPFailure(e.status_code)
示例#30
0
    def create_container(self, container):
        try:
            container_definition = {
                'id': container,
                'indexingPolicy': {
                    'indexingMode':
                    'consistent',  # consistent or lazy
                    'automatic':
                    True,
                    'includedPaths': [{
                        'path':
                        '/*',
                        'indexes': [{
                            'kind': 'Range',
                            'dataType': 'Number',
                            'precision': -1
                        }, {
                            'kind': 'Range',
                            'dataType': 'String',
                            'precision': -1
                        }, {
                            'kind': 'Spatial',
                            'dataType': 'Point'
                        }]
                    }],
                    'excludedPaths': [{
                        'path': '/\'_etag\'/?'
                    }]
                },
                'partitionKey': {
                    'paths': ['/partitionKey'],
                    'kind': 'Hash',
                }
            }

            options = {
                'offerThroughput': 400  # range from 400 to 1 million
            }

            return self.client.CreateContainer(self.database_link,
                                               container_definition, options)

        except errors.CosmosError as e:
            if e.status_code == 409:
                logger.error(
                    'A collection with id \'{0}\' ALREADY exists'.format(
                        self.container_link))
            else:
                raise errors.HTTPFailure(e.status_code)
        except Exception as e:
            raise e