当前位置: 首页>>代码示例>>Python>>正文


Python uuid.uuid4函数代码示例

本文整理汇总了Python中uuid.uuid4函数的典型用法代码示例。如果您正苦于以下问题:Python uuid4函数的具体用法?Python uuid4怎么用?Python uuid4使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了uuid4函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_update_project_returns_extra

    def test_update_project_returns_extra(self):
        """This tests for backwards-compatibility with an essex/folsom bug.

        Non-indexed attributes were returned in an 'extra' attribute, instead
        of on the entity itself; for consistency and backwards compatibility,
        those attributes should be included twice.

        This behavior is specific to the SQL driver.

        """
        tenant_id = uuid.uuid4().hex
        arbitrary_key = uuid.uuid4().hex
        arbitrary_value = uuid.uuid4().hex
        tenant = {
            "id": tenant_id,
            "name": uuid.uuid4().hex,
            "domain_id": DEFAULT_DOMAIN_ID,
            arbitrary_key: arbitrary_value,
        }
        ref = self.identity_man.create_project({}, tenant_id, tenant)
        self.assertEqual(arbitrary_value, ref[arbitrary_key])
        self.assertIsNone(ref.get("extra"))

        tenant["name"] = uuid.uuid4().hex
        ref = self.identity_api.update_project(tenant_id, tenant)
        self.assertEqual(arbitrary_value, ref[arbitrary_key])
        self.assertEqual(arbitrary_value, ref["extra"][arbitrary_key])
开发者ID:brandon-miles,项目名称:keystone,代码行数:27,代码来源:test_backend_sql.py

示例2: test_serializer

    def test_serializer(self):
        transport = _FakeTransport(self.conf)

        serializer = msg_serializer.NoOpSerializer()

        notifier = messaging.Notifier(transport,
                                      'test.localhost',
                                      driver='test',
                                      topic='test',
                                      serializer=serializer)

        message_id = uuid.uuid4()
        self.mox.StubOutWithMock(uuid, 'uuid4')
        uuid.uuid4().AndReturn(message_id)

        timeutils.set_time_override()

        self.mox.StubOutWithMock(serializer, 'serialize_entity')
        serializer.serialize_entity({}, 'bar').AndReturn('sbar')

        self.mox.ReplayAll()

        notifier.info({}, 'test.notify', 'bar')

        message = {
            'message_id': str(message_id),
            'publisher_id': 'test.localhost',
            'event_type': 'test.notify',
            'priority': 'INFO',
            'payload': 'sbar',
            'timestamp': str(timeutils.utcnow.override_time),
        }

        self.assertEquals(_impl_test.NOTIFICATIONS, [({}, message, 'INFO')])
开发者ID:markmc,项目名称:oslo.messaging,代码行数:34,代码来源:test_notifier.py

示例3: test_unauthorized

 def test_unauthorized(self):
     BUCKETNAME = uuid.uuid4().hex
     DESCRIPTION = uuid.uuid4().hex
     result = yield request(
         "POST",
         "%s/%s" % (self.url, BUCKETNAME),
         username=self.username,
         password=self.password,
         data={"description":DESCRIPTION})
     self.assertEqual(result.code, 201)
     result = yield request(
         "GET",
         "%s/%s" % (self.url, BUCKETNAME),
         username="INVALID_USER",
         password="INVALID_PASSWORD")        
     self.assertEqual(result.code, 401)
     result = yield request(
         "GET",
         "%s/%s" % (self.url, BUCKETNAME),
         username=self.username2,
         password=self.password2)        
     self.assertEqual(result.code, 401)
     result = yield request(
         "DELETE",
         "%s/%s" % (self.url, BUCKETNAME),
         username=self.username,
         password=self.password)
     self.assertEqual(result.code, 200)
开发者ID:hiidef,项目名称:hiitrack-api,代码行数:28,代码来源:bucket.py

示例4: get_file_name

    def get_file_name(self, filename):
        """
        Ensures that a file name is unique before uploading.
        The PRMAttachment instance requires an extra attribute,
        partner (a Partner instance) to be set in order to create the
        file name.

        """
        filename, extension = path.splitext(filename)
        filename = '.'.join([sub(r'[\W]', '', filename),
                             sub(r'[\W]', '', extension)])

        # If the uploaded file only contains invalid characters the end
        # result will be a file named "."
        if not filename or filename == '.':
            filename = 'unnamed_file'

        uid = uuid4()
        if self.partner:
            partner = self.partner.pk
            owner = self.partner.owner.pk
        else:
            partner = owner = 'none'
        path_addon = "mypartners/%s/%s/%s" % (owner, partner, uid)
        name = "%s/%s" % (path_addon, filename)

        # Make sure that in the unlikely event that a filepath/uid/filename
        # combination isn't actually unique a new unique id
        # is generated.
        while default_storage.exists(name):
            uid = uuid4()
            path_addon = "mypartners/%s/%s/%s" % (owner, partner, uid)
            name = "%s/%s" % (path_addon, filename)

        return name
开发者ID:kepinq,项目名称:MyJobs,代码行数:35,代码来源:models.py

示例5: test_pqueue_message_time_to_live

def test_pqueue_message_time_to_live(live_servicebus_config, partitioned_queue):
    client = ServiceBusClient(
        service_namespace=live_servicebus_config['hostname'],
        shared_access_key_name=live_servicebus_config['key_name'],
        shared_access_key_value=live_servicebus_config['access_key'],
        debug=True)
    import uuid
    queue_client = client.get_queue(partitioned_queue)
    
    with queue_client.get_sender() as sender:
        content = str(uuid.uuid4())
        message_id = uuid.uuid4()
        message = Message(content)
        message.time_to_live = timedelta(seconds=30)
        sender.send(message)

    time.sleep(30)
    with queue_client.get_receiver() as receiver:
        messages = receiver.fetch_next(timeout=10)
    assert not messages

    with queue_client.get_deadletter_receiver(idle_timeout=5, mode=ReceiveSettleMode.PeekLock) as receiver:
        count = 0
        for message in receiver:
            print_message(message)
            message.complete()
            count += 1
        assert count == 1
开发者ID:Azure,项目名称:azure-sdk-for-python,代码行数:28,代码来源:test_partitioned_queues.py

示例6: test_element_count_validation

 def test_element_count_validation(self):
     """
     Tests that big collections are detected and raise an exception.
     """
     TestMapModel.create(text_map={str(uuid4()): i for i in range(65535)})
     with self.assertRaises(ValidationError):
         TestMapModel.create(text_map={str(uuid4()): i for i in range(65536)})
开发者ID:sakura-sky,项目名称:python-driver,代码行数:7,代码来源:test_container_columns.py

示例7: _test_federated_payload_with_ids

    def _test_federated_payload_with_ids(self, exp_user_id, exp_group_id):
        exp_methods = ['password']
        exp_expires_at = utils.isotime(timeutils.utcnow(), subsecond=True)
        exp_audit_ids = [provider.random_urlsafe_str()]
        exp_federated_info = {'group_ids': [{'id': exp_group_id}],
                              'idp_id': uuid.uuid4().hex,
                              'protocol_id': uuid.uuid4().hex}

        payload = token_formatters.FederatedUnscopedPayload.assemble(
            exp_user_id, exp_methods, exp_expires_at, exp_audit_ids,
            exp_federated_info)

        (user_id, methods, expires_at, audit_ids, federated_info) = (
            token_formatters.FederatedUnscopedPayload.disassemble(payload))

        self.assertEqual(exp_user_id, user_id)
        self.assertEqual(exp_methods, methods)
        self.assertEqual(exp_expires_at, expires_at)
        self.assertEqual(exp_audit_ids, audit_ids)
        self.assertEqual(exp_federated_info['group_ids'][0]['id'],
                         federated_info['group_ids'][0]['id'])
        self.assertEqual(exp_federated_info['idp_id'],
                         federated_info['idp_id'])
        self.assertEqual(exp_federated_info['protocol_id'],
                         federated_info['protocol_id'])
开发者ID:bdelliott,项目名称:keystone,代码行数:25,代码来源:test_fernet_provider.py

示例8: test_consumer_update_normalize_field

    def test_consumer_update_normalize_field(self):
        # If update a consumer with a field with : or - in the name,
        # the name is normalized by converting those chars to _.
        field1_name = 'some:weird-field'
        field1_orig_value = uuid.uuid4().hex

        extra_fields = {field1_name: field1_orig_value}
        consumer = self._consumer_create(**extra_fields)
        consumer_id = consumer['id']

        field1_new_value = uuid.uuid4().hex

        field2_name = 'weird:some-field'
        field2_value = uuid.uuid4().hex

        update_ref = {field1_name: field1_new_value,
                      field2_name: field2_value}

        update_resp = self.patch(self.CONSUMER_URL + '/%s' % consumer_id,
                                 body={'consumer': update_ref})
        consumer = update_resp.result['consumer']

        normalized_field1_name = 'some_weird_field'
        self.assertEqual(field1_new_value, consumer[normalized_field1_name])

        normalized_field2_name = 'weird_some_field'
        self.assertEqual(field2_value, consumer[normalized_field2_name])
开发者ID:roopali8,项目名称:keystone,代码行数:27,代码来源:test_v3_oauth1.py

示例9: forwards

 def forwards(self, orm):
     for award in orm['badges.Award'].objects.all():
         user = award.user
         try:
             user.identity
             current_identity_hash = user.identity.identity_hash
             new_candidate_identity_hash = u'sha256$' + hashlib.sha256(user.email + user.identity.salt).hexdigest()
             if current_identity_hash != new_candidate_identity_hash:
                 salt = uuid.uuid4().hex[:5]
                 user.identity.salt = salt
                 user.identity.identity_hash = u'sha256$' + hashlib.sha256(user.email + salt).hexdigest()
                 user.identity.save()
         except:
             salt = uuid.uuid4().hex[:5]
             orm['badges.Identity'].objects.create(
                 user=user,
                 identity_hash=u'sha256$' + hashlib.sha256(user.email + salt).hexdigest(),
                 salt=salt
             )
         award.uuid = uuid.uuid1()
         award.identity_hash = award.user.identity.identity_hash
         award.identity_type = award.user.identity.type
         award.identity_hashed = award.user.identity.hashed
         award.identity_salt = award.user.identity.salt
         award.expires = None
         award.save()
开发者ID:GeographicaGS,项目名称:moocng,代码行数:26,代码来源:0006_awards_migration.py

示例10: test_multiple_delivery_with_multiple_ack

    def test_multiple_delivery_with_multiple_ack(self):
        data = str(uuid.uuid4())
        data2 = str(uuid.uuid4())
        client = yield self.quick_register(use_webpush=True)
        yield client.disconnect()
        ok_(client.channels)
        yield client.send_notification(data=data)
        yield client.send_notification(data=data2)
        yield client.connect()
        yield client.hello()
        result = yield client.get_notification()
        ok_(result != {})
        ok_(result["data"] in map(urlsafe_b64encode, [data, data2]))
        result2 = yield client.get_notification()
        ok_(result2 != {})
        ok_(result2["data"] in map(urlsafe_b64encode, [data, data2]))
        yield client.ack(result2["channelID"], result2["version"])
        yield client.ack(result["channelID"], result["version"])

        yield client.disconnect()
        yield client.connect()
        yield client.hello()
        result = yield client.get_notification()
        eq_(result, None)
        yield self.shut_down(client)
开发者ID:tomzhang,项目名称:autopush,代码行数:25,代码来源:test_integration.py

示例11: set_image_count

 def set_image_count(self, value):
     '''Add or remove image nodes as needed'''
     assert value > 0
     root = self.root_node
     if self.image_count > value:
         image_nodes = root.find(qn(self.ns['ome'], "Image"))
         for image_node in image_nodes[value:]:
             root.remove(image_node)
     while(self.image_count < value):
         new_image = self.Image(ElementTree.SubElement(root, qn(self.ns['ome'], "Image")))
         new_image.ID = str(uuid.uuid4())
         new_image.Name = "default.png"
         new_image.AcquiredDate = xsd_now()
         new_pixels = self.Pixels(
             ElementTree.SubElement(new_image.node, qn(self.ns['ome'], "Pixels")))
         new_pixels.ID = str(uuid.uuid4())
         new_pixels.DimensionOrder = DO_XYCTZ
         new_pixels.PixelType = PT_UINT8
         new_pixels.SizeC = 1
         new_pixels.SizeT = 1
         new_pixels.SizeX = 512
         new_pixels.SizeY = 512
         new_pixels.SizeZ = 1
         new_channel = self.Channel(
             ElementTree.SubElement(new_pixels.node, qn(self.ns['ome'], "Channel")))
         new_channel.ID = "Channel%d:0" % self.image_count
         new_channel.Name = new_channel.ID
         new_channel.SamplesPerPixel = 1
开发者ID:ilia-kats,项目名称:python-bioformats,代码行数:28,代码来源:omexml.py

示例12: test_validation_error

 def test_validation_error(self):
     target = uuid.uuid4().hex
     attribute = uuid.uuid4().hex
     e = exception.ValidationError(target=target, attribute=attribute)
     self.assertValidJsonRendering(e)
     self.assertIn(target, six.text_type(e))
     self.assertIn(attribute, six.text_type(e))
开发者ID:cyan-cliqr,项目名称:keystone,代码行数:7,代码来源:test_exception.py

示例13: test_dup_domain

    def test_dup_domain(self):
        openstack_driver = FakeExtensionManager.get_extension_objects("vnc_cfg_api.resync")[0]
        orig_ks_domains_list = openstack_driver._ks_domains_list
        orig_ks_domain_get = openstack_driver._ks_domain_get
        try:
            openstack_driver._ks_domains_list = openstack_driver._ksv3_domains_list
            openstack_driver._ks_domain_get = openstack_driver._ksv3_domain_get
            logger.info('Creating first domain in "keystone"')
            dom_id = str(uuid.uuid4())
            dom_name = self.id()
            test_case.get_keystone_client().domains.add_domain(dom_id, dom_name)
            dom_obj = self._vnc_lib.domain_read(id=dom_id)
            self.assertThat(dom_obj.name, Equals(dom_name))

            logger.info('Creating second domain with same name diff id in "keystone"')
            new_dom_id = str(uuid.uuid4())
            test_case.get_keystone_client().domains.add_domain(new_dom_id, dom_name)
            new_dom_obj = self._vnc_lib.domain_read(id=new_dom_id)
            self.assertThat(new_dom_obj.name, Not(Equals(dom_name)))
            self.assertThat(new_dom_obj.name, Contains(dom_name))

            self._vnc_lib.domain_delete(id=dom_id)
            self._vnc_lib.domain_delete(id=new_dom_id)
        finally:
            openstack_driver._ks_domains_list = orig_ks_domains_list
            openstack_driver._ks_domain_get = orig_ks_domain_get
开发者ID:secof,项目名称:contrail-controller,代码行数:26,代码来源:test_naming.py

示例14: vios_to_vios_auth

def vios_to_vios_auth(source, dest, conn_info):
    """Context allowing for SSH between VIOS partitions

    This context will build an SSH key on the source host, put the key
    into the authorized_keys on the destination host, and make the
    private key file name available within the context.
    The key files and key inserted into authorized_keys will be
    removed when the context exits.

    :param source: source IP or DNS name
    :param dest: destination IP or DNS name
    :param conn_info: dictionary object with SSH connection
                      information for both hosts
    """
    KEY_BASE_NAME = "os-%s" % uuid.uuid4().hex
    keypair_uuid = uuid.uuid4()
    src_conn_obj = ssh_connect(conn_info)

    dest_conn_info = Connection(dest, conn_info.username,
                                       conn_info.password)
    dest_conn_obj = ssh_connect(dest_conn_info)

    def run_command(conn_obj, cmd):
        stdout, stderr = processutils.ssh_execute(conn_obj, cmd)
        return stdout.strip().splitlines()

    def build_keypair_on_source():
        mkkey = ('ssh-keygen -f %s -N "" -C %s' %
                    (KEY_BASE_NAME, keypair_uuid.hex))
        ssh_command_as_root(src_conn_obj, mkkey)

        chown_key = ('chown %s %s*' % (conn_info.username, KEY_BASE_NAME))
        ssh_command_as_root(src_conn_obj, chown_key)

        cat_key = ('cat %s.pub' % KEY_BASE_NAME)
        pubkey = run_command(src_conn_obj, cat_key)

        return pubkey[0]

    def cleanup_key_on_source():
        rmkey = 'rm %s*' % KEY_BASE_NAME
        run_command(src_conn_obj, rmkey)

    def insert_into_authorized_keys(public_key):
        echo_key = 'echo "%s" >> .ssh/authorized_keys' % public_key
        ssh_command_as_root(dest_conn_obj, echo_key)

    def remove_from_authorized_keys():
        rmkey = ('sed /%s/d .ssh/authorized_keys > .ssh/authorized_keys' %
                 keypair_uuid.hex)
        ssh_command_as_root(dest_conn_obj, rmkey)

    public_key = build_keypair_on_source()
    insert_into_authorized_keys(public_key)

    try:
        yield KEY_BASE_NAME
    finally:
        remove_from_authorized_keys()
        cleanup_key_on_source()
开发者ID:windskyer,项目名称:k_nova,代码行数:60,代码来源:common.py

示例15: execute

 def execute(self, code):
     if debug:
         execute_request = Msg(["execute_request"],
         {"msg_id": "07033084-5cfd-4812-90a4-e4d24ffb6e3d", 
          "username": str(self.id), 
          "session": "07033084-5cfd-4812-90a4-e4d24ffb6e3d", 
          "msg_type": "execute_request"}, 
          {"code": code, 
           "silent": False, 
           "store_history": False, 
           "user_variables": list(), 
           "user_expressions": {}, 
           "allow_stdin": True}, {})
     else:
         execute_request = Msg(["execute_request"],
         {"msg_id": str(uuid.uuid4()), 
          "username": str(self.id), 
          "session": str(uuid.uuid4()), 
          "msg_type": "execute_request"}, 
          {"code": code, 
           "silent": False, 
           "store_history": False, 
           "user_variables": list(), 
           "user_expressions": {}, 
           "allow_stdin": True}, {})
     ret = self.shell.send(execute_request)
开发者ID:cbecker,项目名称:Sublime-IJulia,代码行数:26,代码来源:Kernel.py


注:本文中的uuid.uuid4函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。