Python uuid.uuid4() Examples

The following are code examples for showing how to use uuid.uuid4(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: alfred-yubikey-otp   Author: robertoriv   File: workflow3.py    MIT License 6 votes vote down vote up
def session_id(self):
        """A unique session ID every time the user uses the workflow.

        .. versionadded:: 1.25

        The session ID persists while the user is using this workflow.
        It expires when the user runs a different workflow or closes
        Alfred.

        """
        if not self._session_id:
            from uuid import uuid4
            self._session_id = uuid4().hex
            self.setvar('_WF_SESSION_ID', self._session_id)

        return self._session_id 
Example 2
Project: hydrus   Author: HTTP-APIs   File: test_app.py    MIT License 6 votes vote down vote up
def test_object_PUT_at_id(self):
        """Create object in collection using PUT at specific ID."""
        index = self.client.get("/{}".format(self.API_NAME))
        assert index.status_code == 200
        endpoints = json.loads(index.data.decode('utf-8'))
        for endpoint in endpoints:
            collection_name = "/".join(endpoints[endpoint].split(
                "/{}/".format(self.API_NAME))[1:])
            if collection_name in self.doc.collections:
                collection = self.doc.collections[collection_name]["collection"]
                class_ = self.doc.parsed_classes[collection.class_.title]["class"]
                class_methods = [x.method for x in class_.supportedOperation]
                dummy_object = gen_dummy_object(
                    collection.class_.title, self.doc)
                if "PUT" in class_methods:
                    dummy_object = gen_dummy_object(
                        collection.class_.title, self.doc)
                    put_response = self.client.put('{}/{}'.format(
                        endpoints[endpoint], uuid.uuid4()), data=json.dumps(dummy_object))
                    assert put_response.status_code == 201 
Example 3
Project: hydrus   Author: HTTP-APIs   File: test_app.py    MIT License 6 votes vote down vote up
def setUp(self):
        for class_ in self.doc.parsed_classes:
            class_title = self.doc.parsed_classes[class_]["class"].title
            dummy_obj = gen_dummy_object(class_title, self.doc)
            crud.insert(
                dummy_obj,
                id_=str(
                    uuid.uuid4()),
                session=self.session)
            # If it's a collection class then add an extra object so
            # we can test pagination thoroughly.
            if class_ in self.doc.collections:
                crud.insert(
                    dummy_obj,
                    id_=str(
                        uuid.uuid4()),
                    session=self.session)
        # Add two dummy modification records
        crud.insert_modification_record(method="POST",
                                        resource_url="", session=self.session)
        crud.insert_modification_record(method="DELETE",
                                        resource_url="", session=self.session) 
Example 4
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 6 votes vote down vote up
def test_update(self):
        """Test CRUD update."""
        random_class = random.choice(self.doc_collection_classes)
        object_ = gen_dummy_object(random_class, self.doc)
        new_object = gen_dummy_object(random_class, self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        update_response = crud.update(
            id_=id_,
            type_=object_["@type"],
            object_=new_object,
            session=self.session,
            api_name="api")
        test_object = crud.get(id_=id_, type_=object_[
                               "@type"], session=self.session, api_name="api")
        assert isinstance(insert_response, str)
        assert isinstance(update_response, str)
        assert insert_response == update_response
        assert test_object["@id"].split("/")[-1] == id_ 
Example 5
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 6 votes vote down vote up
def test_delete(self):
        """Test CRUD delete."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        delete_response = crud.delete(
            id_=id_, type_=object_["@type"], session=self.session)
        assert isinstance(insert_response, str)
        response_code = None
        try:
            get_response = crud.get(
                id_=id_,
                type_=object_["@type"],
                session=self.session,
                api_name="api")
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 404 == response_code 
Example 6
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 6 votes vote down vote up
def test_delete_type(self):
        """Test CRUD delete when wrong/undefined class is given."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        assert isinstance(insert_response, str)
        assert insert_response == id_
        response_code = None
        try:
            delete_response = crud.delete(
                id_=id_, type_="otherClass", session=self.session)
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 400 == response_code 
Example 7
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 6 votes vote down vote up
def test_delete_id(self):
        """Test CRUD delete when wrong/undefined ID is given."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        response_code = None
        try:
            delete_response = crud.delete(
                id_=999, type_=object_["@type"], session=self.session)
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 404 == response_code
        assert isinstance(insert_response, str)
        assert insert_response == id_ 
Example 8
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 6 votes vote down vote up
def test_delete_ids(self):
        objects = list()
        ids = "{},{}".format(str(uuid.uuid4()), str(uuid.uuid4()))
        for index in range(len(ids.split(','))):
            object = gen_dummy_object(random.choice(
                self.doc_collection_classes), self.doc)
            objects.append(object)
        insert_response = crud.insert_multiple(objects_=objects,
                                               session=self.session, id_=ids)
        delete_response = crud.delete_multiple(
            id_=ids, type_=objects[0]["@type"], session=self.session)

        response_code = None
        id_list = ids.split(',')
        try:
            for index in range(len(id_list)):
                get_response = crud.get(
                    id_=id_list[index],
                    type_=objects[index]["@type"],
                    session=self.session,
                    api_name="api")
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 404 == response_code 
Example 9
Project: pyblish-win   Author: pyblish   File: test_uuid.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testIssue8621(self):
        # On at least some versions of OSX uuid.uuid4 generates
        # the same sequence of UUIDs in the parent and any
        # children started using fork.
        fds = os.pipe()
        pid = os.fork()
        if pid == 0:
            os.close(fds[0])
            value = uuid.uuid4()
            os.write(fds[1], value.hex)
            os._exit(0)

        else:
            os.close(fds[1])
            self.addCleanup(os.close, fds[0])
            parent_value = uuid.uuid4().hex
            os.waitpid(pid, 0)
            child_value = os.read(fds[0], 100)

            self.assertNotEqual(parent_value, child_value) 
Example 10
Project: drydock   Author: airshipit   File: test_postgres_builddata.py    Apache License 2.0 6 votes vote down vote up
def test_build_data_insert_iwth_collected_date(self, blank_state):
        """Test that build data can be inserted specifying collection date."""
        build_data_fields = {
            'node_name': 'foo',
            'generator': 'hello_world',
            'data_format': 'text/plain',
            'data_element': 'Hello World!',
            'task_id': uuid.uuid4(),
            'collected_date': datetime.utcnow(),
        }

        build_data = objects.BuildData(**build_data_fields)

        result = blank_state.post_build_data(build_data)

        assert result 
Example 11
Project: drydock   Author: airshipit   File: test_postgres_builddata.py    Apache License 2.0 6 votes vote down vote up
def test_build_data_select(self, blank_state):
        """Test that build data can be deserialized from the database."""
        build_data_fields = {
            'node_name': 'foo',
            'generator': 'hello_world',
            'data_format': 'text/plain',
            'data_element': 'Hello World!',
            'task_id': uuid.uuid4(),
            'collected_date': datetime.utcnow(),
        }

        build_data = objects.BuildData(**build_data_fields)

        result = blank_state.post_build_data(build_data)

        assert result

        bd_list = blank_state.get_build_data()

        assert len(bd_list) == 1

        assert bd_list[0].to_dict() == build_data.to_dict() 
Example 12
Project: drydock   Author: airshipit   File: test_maasdriver_network.py    Apache License 2.0 6 votes vote down vote up
def test_maas_fabric(self):
        client_config = config.DrydockConfig.node_driver['maasdriver']

        maas_client = client.MaasRequestFactory(client_config['api_url'],
                                                client_config['api_key'])

        fabric_name = str(uuid.uuid4())

        fabric_list = maas_fabric.Fabrics(maas_client)
        fabric_list.refresh()

        test_fabric = maas_fabric.Fabric(
            maas_client, name=fabric_name, description='Test Fabric')
        test_fabric = fabric_list.add(test_fabric)

        assert test_fabric.name == fabric_name
        assert test_fabric.resource_id is not None

        query_fabric = maas_fabric.Fabric(
            maas_client, resource_id=test_fabric.resource_id)
        query_fabric.refresh()

        assert query_fabric.name == test_fabric.name 
Example 13
Project: drydock   Author: airshipit   File: test_auth_middleware.py    Apache License 2.0 6 votes vote down vote up
def test_process_request_user(self):
        ''' AuthMiddleware is expected to correctly identify the headers
            added to an authenticated request by keystonemiddleware in a
            PasteDeploy configuration
        '''

        req_env = TestAuthMiddleware.ks_user_env

        project_id = str(uuid.uuid4().hex)
        req_env['HTTP_X_PROJECT_ID'] = project_id
        user_id = str(uuid.uuid4().hex)
        req_env['HTTP_X_USER_ID'] = user_id
        token = str(uuid.uuid4().hex)
        req_env['HTTP_X_AUTH_TOKEN'] = token

        middleware = AuthMiddleware()
        request = DrydockRequest(req_env)
        response = falcon.Response()

        middleware.process_request(request, response)

        assert request.context.authenticated
        assert request.context.user_id == user_id 
Example 14
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow3.py    MIT License 6 votes vote down vote up
def session_id(self):
        """A unique session ID every time the user uses the workflow.

        .. versionadded:: 1.25

        The session ID persists while the user is using this workflow.
        It expires when the user runs a different workflow or closes
        Alfred.

        """
        if not self._session_id:
            from uuid import uuid4
            self._session_id = uuid4().hex
            self.setvar('_WF_SESSION_ID', self._session_id)

        return self._session_id 
Example 15
Project: everyclass-server   Author: everyclass   File: dao.py    Mozilla Public License 2.0 6 votes vote down vote up
def insert_calendar_token(cls, resource_type: str, semester: str, identifier: str) -> str:
        """
        生成日历令牌,写入数据库并返回字符串类型的令牌。此时的 last_used_time 是 NULL。

        :param resource_type: student/teacher
        :param semester: 学期字符串
        :param identifier: 学号或教工号
        :return: token 字符串
        """
        token = uuid.uuid4()

        with pg_conn_context() as conn, conn.cursor() as cursor:
            insert_query = """
            INSERT INTO calendar_tokens (type, identifier, semester, token, create_time)
                VALUES (%s,%s,%s,%s,%s);
            """
            cursor.execute(insert_query, (resource_type, identifier, semester, token, datetime.datetime.now()))
            conn.commit()
        return str(token) 
Example 16
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getFileKey(cls, filepath, salt='', custom_key=''):
        today = str(datetime.date.today())
        filename = os.path.basename(filepath)
        if not salt:
            salt = today + '-' + uuid.uuid4().hex[:8]
            if custom_key:
                salt = custom_key + '-' + salt
        if salt.startswith('s-') or salt.startswith('su-'):
            # Session-user key
            fhead = os.path.splitext(filename)[0]
            if '--' in fhead:
                sep = '--'
            else:
                sep = '-'   # For legacy compatibility only

            fprefix, _, uname = fhead.rpartition(sep)
            sname, _, _ = fprefix.partition(sep)
            if salt.startswith('s-'):
                hmac_key = sliauth.gen_file_key(Options['auth_key'], sname, '')
            else:
                hmac_key = sliauth.gen_file_key(Options['auth_key'], sname, uname, timestamp=today)
        else:
            hmac_key = Options['auth_key']
        subkey = sliauth.gen_hmac_token(hmac_key, salt+':'+filename)
        return sliauth.safe_quote(salt+':'+subkey) 
Example 17
Project: slidoc   Author: mitotic   File: sdstream.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def oauth_request_parameters(consumer_token, url, access_token, parameters={},
                             method="GET", oauth_version="1.0a",
                             override_version=""):
    base_args = dict(
        oauth_consumer_key=consumer_token["key"],
        oauth_token=access_token["key"],
        oauth_signature_method="HMAC-SHA1",
        oauth_timestamp=str(int(time.time())),
        oauth_nonce=binascii.b2a_hex(uuid.uuid4().bytes),
        oauth_version=override_version or oauth_version,
    )
    args = base_args.copy()
    args.update(parameters)
    if oauth_version == "1.0a":
        signature = tornado.auth._oauth10a_signature(consumer_token, method, url, args, access_token)
    else:
        signature = tornado.auth._oauth_signature(consumer_token, method, url, args, access_token)
    base_args["oauth_signature"] = signature
    return base_args 
Example 18
Project: reroils-data-legacy   Author: rero   File: api.py    GNU General Public License v2.0 6 votes vote down vote up
def receive_item(self, transaction_member_pid, **kwargs):
        """Receive an item."""
        item = self.dumps()
        id = str(uuid4())
        item_member_pid = item['member_pid']
        first_request = self.get_first_request()
        has_requests = self.number_of_item_requests() > 0
        if not has_requests and item_member_pid == transaction_member_pid:
            self['_circulation']['status'] = ItemStatus.ON_SHELF
        elif (has_requests and
              first_request['pickup_member_pid'] == transaction_member_pid):
            self['_circulation']['status'] = ItemStatus.AT_DESK
            item_at_desk.send(
                current_app._get_current_object(),
                item=self
            )
        else:
            self['_circulation']['status'] = ItemStatus.IN_TRANSIT
        data = self.build_data(0, 'receive_item_request')
        CircTransaction.create(data, id=id) 
Example 19
Project: reroils-data-legacy   Author: rero   File: api.py    GNU General Public License v2.0 6 votes vote down vote up
def validate_item_request(self, **kwargs):
        """Validate item request."""
        id = str(uuid4())
        if self.number_of_item_requests():
            first_request = self.get_first_request()
            pickup_member_pid = first_request['pickup_member_pid']
            location_pid = self.get('location_pid')
            location = Location.get_record_by_pid(location_pid)
            member = MemberWithLocations.get_member_by_locationid(location.id)
            member_pid = member.pid
            if member_pid == pickup_member_pid:
                self['_circulation']['status'] = ItemStatus.AT_DESK
                item_at_desk.send(
                    current_app._get_current_object(),
                    item=self
                )
            else:
                self['_circulation']['status'] = ItemStatus.IN_TRANSIT
            data = self.build_data(0, 'validate_item_request')
            CircTransaction.create(data, id=id)
        else:
            raise PIDInvalidAction() 
Example 20
Project: reroils-data-legacy   Author: rero   File: api.py    GNU General Public License v2.0 6 votes vote down vote up
def extend_loan(
            self, requested_end_date=None, renewal_count=None, **kwargs
    ):
        """Request a new end date for the active loan.

        A possible status ItemStatus.OVERDUE will be removed.
        """
        id = str(uuid4())
        if not renewal_count:
            renewal_count = self.get_renewal_count() + 1
        if not requested_end_date:
            request_date = datetime.today() + timedelta(self.duration)
            requested_end_date = datetime.strftime(request_date, '%Y-%m-%d')
        self.holdings[0]['end_date'] = requested_end_date
        self.holdings[0]['renewal_count'] = renewal_count
        CircTransaction.create(self.build_data(0, 'extend_item_loan'), id=id) 
Example 21
Project: reroils-data-legacy   Author: rero   File: test_locations_minters.py    GNU General Public License v2.0 6 votes vote down vote up
def test_location_id_minter(db):
    """Test location_id minter."""
    data = {}
    # first record
    rec_uuid = uuid4()
    pid1 = minters.location_id_minter(rec_uuid, data)
    assert pid1
    assert data['pid'] == pid1.pid_value
    assert data['pid'] == '1'
    assert pid1.object_type == 'rec'
    assert pid1.object_uuid == rec_uuid

    # second record
    data = {}
    rec_uuid = uuid4()
    pid2 = minters.location_id_minter(rec_uuid, data)
    assert data['pid'] == '2' 
Example 22
Project: reroils-data-legacy   Author: rero   File: test_documents_minters.py    GNU General Public License v2.0 6 votes vote down vote up
def test_document_id_minter(db):
    """Test document_id minter."""
    data = {}
    # first record
    rec_uuid = uuid4()
    pid1 = minters.document_id_minter(rec_uuid, data)
    assert pid1
    assert data['pid'] == pid1.pid_value
    assert data['pid'] == '1'
    assert pid1.object_type == 'rec'
    assert pid1.object_uuid == rec_uuid

    # second record
    data = {}
    rec_uuid = uuid4()
    pid2 = minters.document_id_minter(rec_uuid, data)
    assert data['pid'] == '2' 
Example 23
Project: fs_image   Author: facebookincubator   File: nspawn_in_subvol.py    MIT License 5 votes vote down vote up
def _nspawn_cmd(nspawn_subvol):
    return [
        # Without this, nspawn would look for the host systemd's cgroup setup,
        # which breaks us in continuous integration containers, which may not
        # have a `systemd` in the host container.
        #
        # We set this variable via `env` instead of relying on the `sudo`
        # configuration because it's important that it be set.
        'env', 'UNIFIED_CGROUP_HIERARCHY=yes',
        'systemd-nspawn',
        # These are needed since we do not want to require a working `dbus` on
        # the host.
        '--register=no', '--keep-unit',
        # Randomize --machine so that the container has a random hostname
        # each time. The goal is to help detect builds that somehow use the
        # hostname to influence the resulting image.
        '--machine', uuid.uuid4().hex,
        '--directory', nspawn_subvol.path(),
        *_inject_os_release_args(nspawn_subvol),
        # Don't pollute the host's /var/log/journal
        '--link-journal=no',
        # Explicitly do not look for any settings for our ephemeral machine
        # on the host.
        '--settings=no',
        # Test containers probably should not be accessing host devices, so
        # take that away until proven necessary.
        '--drop-capability=CAP_MKNOD',
        # The timezone should be set up explicitly, not by nspawn's fiat.
        '--timezone=off',  # requires v239+
        # Future: Uncomment.  This is good container hygiene.  It had to go
        # since it breaks XAR binaries, which rely on a setuid bootstrap.
        # '--no-new-privileges=1',
    ] 
Example 24
Project: fs_image   Author: facebookincubator   File: filesystem_storage.py    MIT License 5 votes vote down vote up
def writer(self) -> ContextManager[StorageOutput]:
        sid = str(uuid.uuid4()).replace('-', '')
        sid_path = self._path_for_storage_id(sid)
        try:
            os.makedirs(sid_path.dirname())
        except FileExistsError:  # pragma: no cover
            pass

        with os.fdopen(os.open(
            sid_path,
            os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC,
            mode=stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH,
        ), 'wb') as outfile:

            @contextmanager
            def get_id_and_release_resources():
                try:
                    yield sid
                finally:
                    # This `close()` flushes, making the written data readable,
                    # and prevents more writes via `StorageOutput`.
                    outfile.close()

            # `_CommitCallback` has a `try` to clean up on error. This
            # placement of the context assumes that `os.fdopen` cannot fail.
            with _CommitCallback(self, get_id_and_release_resources) as commit:
                yield StorageOutput(output=outfile, commit_callback=commit) 
Example 25
Project: fs_image   Author: facebookincubator   File: rpm_action.py    MIT License 5 votes vote down vote up
def _yum_dnf_using_build_appliance(
    *, build_appliance: Subvol,
    nspawn_args: List[str],
    install_root: Path,
    protected_paths: Iterable[str],
    yum_dnf_args: List[str],
    layer_opts: LayerOpts,
) -> None:
    work_dir = '/work' + base64.urlsafe_b64encode(
        uuid.uuid4().bytes  # base64 instead of hex saves 10 bytes
    ).decode().strip('=')
    prog_name = _get_yum_or_dnf(build_appliance, layer_opts)
    mount_cache = '' if layer_opts.preserve_yum_dnf_cache else f'''
        mkdir -p {work_dir}/var/cache/{prog_name} ; \
        mount --bind /var/cache/{prog_name} {work_dir}/var/cache/{prog_name} ;
    '''
    opts = nspawn_in_subvol_parse_opts([
        '--layer', 'UNUSED',
        '--user', 'root',
        # You can see below --no-private-network in conjunction with
        # --cap-net-admin.  CAP_NET_ADMIN is not intended to administer the
        # host's network stack.  See how yum_dnf_from_snapshot() brings
        # loopback interface up under protection of "unshare --net".
        '--cap-net-admin',
        '--no-private-network',
        '--bindmount-rw', install_root.decode(), work_dir,
        *nspawn_args,
        '--', 'sh', '-uec',
        f'''
        {mount_cache}
        /rpm-repo-snapshot/default/bin/{prog_name} \
            {' '.join(
                '--protected-path=' + shlex.quote(p) for p in protected_paths
            )} \
            --install-root {work_dir} \
            -- {' '.join(shlex.quote(arg) for arg in yum_dnf_args)}
        ''',
    ])
    # Don't pollute stdout with logging
    nspawn_in_subvol(build_appliance, opts, stdout=sys.stderr) 
Example 26
Project: invenio-openaire   Author: inveniosoftware   File: test_loaders.py    MIT License 5 votes vote down vote up
def test_remote_openaire_loader(app, db):
    """Test the remote OAI-PMH OpenAIRE loader."""
    loader = RemoteOAIRELoader()
    pytest.raises(OAIRELoadingError, list, loader.iter_grants())

    recuuid = uuid.uuid4()
    PersistentIdentifier.create(
        'frdoi', '10.13039/501100000925',
        object_type='rec', object_uuid=recuuid, status='R')
    Record.create({'acronyms': ['EC']}, id_=recuuid)

    records = list(loader.iter_grants())
    assert len(records) == 5 
Example 27
Project: invenio-openaire   Author: inveniosoftware   File: test_loaders.py    MIT License 5 votes vote down vote up
def test_oaire_dumper(db, sqlite_tmpdb):
    """Test the grants dumper to local destination."""
    recuuid = uuid.uuid4()
    PersistentIdentifier.create(
        'frdoi', '10.13039/501100000925',
        object_type='rec', object_uuid=recuuid, status='R')
    Record.create({'acronyms': ['EC']}, id_=recuuid)
    dumper = OAIREDumper(destination=sqlite_tmpdb)

    # We expect to harvest 5 record from the MockSickle.
    # with 'commit_batch_size=2', we will make 3 commits to sqlite db
    dumper.dump(commit_batch_size=2)
    loader = LocalOAIRELoader(source=sqlite_tmpdb)
    records = list(loader.iter_grants())
    assert len(records) == 5 
Example 28
Project: invenio-openaire   Author: inveniosoftware   File: test_fetchers.py    MIT License 5 votes vote down vote up
def test_funder_fetcher():
    """Test funder fetcher."""
    val = '10.13039/001'
    pid = funder_fetcher(uuid.uuid4(), dict(doi=val))
    assert pid.provider is None
    assert pid.pid_type is 'frdoi'
    assert pid.pid_value is val 
Example 29
Project: invenio-openaire   Author: inveniosoftware   File: test_fetchers.py    MIT License 5 votes vote down vote up
def test_grant_fetcher():
    """Test grant fetcher."""
    val = '10.13039/001::01'
    pid = grant_fetcher(uuid.uuid4(), dict(internal_id=val))
    assert pid.provider is None
    assert pid.pid_type is 'grant'
    assert pid.pid_value is val 
Example 30
Project: hydrus   Author: HTTP-APIs   File: user.py    MIT License 5 votes vote down vote up
def create_nonce(session: Session) -> str:
    """
    Create a one time use nonce valid for a short time
    for user authentication.
    """
    nonce = str(uuid4())
    time = datetime.now()
    new_nonce = Nonce(id=nonce, timestamp=time)
    session.add(new_nonce)
    session.commit()
    return nonce 
Example 31
Project: hydrus   Author: HTTP-APIs   File: test_app.py    MIT License 5 votes vote down vote up
def setUp(self):
        for class_ in self.doc.parsed_classes:
            link_props = {}
            class_title = self.doc.parsed_classes[class_]["class"].title
            dummy_obj = gen_dummy_object(class_title, self.doc)
            for supportedProp in self.doc.parsed_classes[class_]['class'].supportedProperty:
                if isinstance(supportedProp.prop, HydraLink):
                    class_name = supportedProp.prop.range.replace("vocab:", "")
                    for collection_path in self.doc.collections:
                        coll_class = self.doc.collections[
                            collection_path]['collection'].class_.title
                        if class_name == coll_class:
                            id_ = str(uuid.uuid4())
                            crud.insert(
                                gen_dummy_object(class_name, self.doc),
                                id_=id_,
                                session=self.session)
                            link_props[supportedProp.title] = id_
                            dummy_obj[supportedProp.title] = "{}/{}/{}".format(
                                self.API_NAME, collection_path, id_)
            crud.insert(
                dummy_obj,
                id_=str(
                    uuid.uuid4()),
                link_props=link_props,
                session=self.session)
            # If it's a collection class then add an extra object so
            # we can test pagination thoroughly.
            if class_ in self.doc.collections:
                crud.insert(
                    dummy_obj,
                    id_=str(
                        uuid.uuid4()),
                    session=self.session) 
Example 32
Project: hydrus   Author: HTTP-APIs   File: test_app.py    MIT License 5 votes vote down vote up
def test_object_PUT_at_ids(self):
        index = self.client.get("/{}".format(self.API_NAME))
        assert index.status_code == 200
        endpoints = json.loads(index.data.decode('utf-8'))
        for endpoint in endpoints:
            collection_name = "/".join(endpoints[endpoint].split(
                "/{}/".format(self.API_NAME))[1:])
            if collection_name in self.doc.collections:
                collection = self.doc.collections[collection_name]["collection"]
                class_ = self.doc.parsed_classes[collection.class_.title]["class"]
                class_methods = [x.method for x in class_.supportedOperation]
                data_ = {"data": list()}
                objects = list()
                ids = ""
                for index in range(3):
                    objects.append(gen_dummy_object(
                        collection.class_.title, self.doc))
                    ids = "{},".format(uuid.uuid4())
                data_["data"] = objects
                if "PUT" in class_methods:
                    put_response = self.client.put(
                        '{}/add/{}'.format(endpoints[endpoint], ids),
                        data=json.dumps(data_))
                    assert put_response.status_code == 201 
Example 33
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 5 votes vote down vote up
def test_get(self):
        """Test CRUD get."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        response = crud.insert(object_=object_, id_=id_, session=self.session)
        object_ = crud.get(id_=id_, type_=object_[
                           "@type"], session=self.session, api_name="api")
        assert isinstance(response, str)
        assert object_["@id"].split("/")[-1] == id_ 
Example 34
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 5 votes vote down vote up
def test_get_for_nested_obj(self):
        """Test get operation for object that can contain other objects."""
        for class_ in self.doc_collection_classes:
            for prop in self.doc.parsed_classes[class_]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink) or "vocab:" in prop.prop:
                    link_props = {}
                    dummy_obj = gen_dummy_object(class_, self.doc)
                    if isinstance(prop.prop, HydraLink):
                        nested_class = prop.prop.range.replace("vocab:", "")
                        for collection_path in self.doc.collections:
                            coll_class = self.doc.collections[
                                collection_path]['collection'].class_.title
                            if nested_class == coll_class:
                                id_ = str(uuid.uuid4())
                                crud.insert(
                                    gen_dummy_object(nested_class, self.doc),
                                    id_=id_,
                                    session=self.session)
                                link_props[prop.title] = id_
                                dummy_obj[prop.title] = "{}/{}/{}".format(
                                    self.API_NAME, collection_path, id_)
                    else:
                        nested_class = prop.prop.replace("vocab:", "")
                    obj_id = str(uuid.uuid4())
                    response = crud.insert(object_=dummy_obj, id_=obj_id,
                                           link_props=link_props, session=self.session)
                    object_ = crud.get(id_=obj_id, type_=class_, session=self.session,
                                       api_name="api")
                    assert prop.title in object_
                    nested_obj_id = object_[prop.title]
                    nested_obj = crud.get(id_=nested_obj_id, type_=nested_class,
                                          session=self.session, api_name="api")
                    assert nested_obj["@id"].split("/")[-1] == nested_obj_id
                    break 
Example 35
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 5 votes vote down vote up
def test_get_type(self):
        """Test CRUD get when wrong/undefined class is given."""
        id_ = str(uuid.uuid4())
        type_ = "otherClass"
        response_code = None
        try:
            get_response = crud.get(
                id_=id_, type_=type_, session=self.session, api_name="api")
        except Exception as e:
            error = e.get_HTTP()
        assert 400 == error.code 
Example 36
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 5 votes vote down vote up
def test_insert_type(self):
        """Test CRUD insert when wrong/undefined class is given."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        object_["@type"] = "otherClass"
        response_code = None
        try:
            insert_response = crud.insert(
                object_=object_, id_=id_, session=self.session)
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 400 == response_code 
Example 37
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 5 votes vote down vote up
def test_insert_used_id(self):
        """Test CRUD insert when used ID is given."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        response_code = None
        try:
            insert_response = crud.insert(
                object_=object_, id_=id_, session=self.session)
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 400 == response_code 
Example 38
Project: hydrus   Author: HTTP-APIs   File: test_cli.py    MIT License 5 votes vote down vote up
def setUp(self):
        for class_ in self.doc.parsed_classes:
            if class_ not in self.doc.collections:
                class_type = self.doc.parsed_classes[class_]['class'].title
                dummy_obj = gen_dummy_object(class_type, self.doc)
                crud.insert(
                    dummy_obj,
                    id_=str(
                        uuid.uuid4()),
                    session=self.session) 
Example 39
Project: pyblish-win   Author: pyblish   File: test_uuid.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_uuid4(self):
        equal = self.assertEqual

        # Make sure uuid4() generates UUIDs that are actually version 4.
        for u in [uuid.uuid4() for i in range(10)]:
            equal(u.variant, uuid.RFC_4122)
            equal(u.version, 4)

        # Make sure the generated UUIDs are actually unique.
        uuids = {}
        for u in [uuid.uuid4() for i in range(1000)]:
            uuids[u] = 1
        equal(len(uuids.keys()), 1000) 
Example 40
Project: flaskit   Author: elston   File: database.py    MIT License 5 votes vote down vote up
def set_id(self):
        self.id = uuid.uuid4() 
Example 41
Project: drydock   Author: airshipit   File: base.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.log_level = 'ERROR'
        self.user = None  # Username
        self.user_id = None  # User ID (UUID)
        self.user_domain_id = None  # Domain owning user
        self.roles = []
        self.project_id = None
        self.project_domain_id = None  # Domain owning project
        self.is_admin_project = False
        self.authenticated = False
        self.request_id = str(uuid.uuid4())
        self.external_marker = ''
        self.policy_engine = None
        self.end_user = None  # Initial User 
Example 42
Project: drydock   Author: airshipit   File: task.py    Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 action=None,
                 design_ref=None,
                 parent_task_id=None,
                 node_filter=None,
                 context=None,
                 statemgr=None,
                 retry=0):
        self.statemgr = statemgr

        self.task_id = uuid.uuid4()
        self.status = hd_fields.TaskStatus.Requested
        self.subtask_id_list = []
        self.result = TaskStatus()
        self.action = action or hd_fields.OrchestratorAction.Noop
        self.design_ref = design_ref
        self.retry = retry
        self.parent_task_id = parent_task_id
        self.created = datetime.utcnow()
        self.node_filter = copy.deepcopy(node_filter)
        self.created_by = None
        self.updated = None
        self.terminated = None
        self.terminated_by = None
        self.request_context = context
        self.terminate = False
        self.logger = logging.getLogger("drydock")

        if context is not None:
            self.created_by = context.user 
Example 43
Project: drydock   Author: airshipit   File: site.py    Apache License 2.0 5 votes vote down vote up
def assign_id(self):
        self.id = uuid.uuid4()
        return self.id

    # SiteDesign Keyed by id 
Example 44
Project: drydock   Author: airshipit   File: partition.py    Apache License 2.0 5 votes vote down vote up
def format(self, fstype='ext4', uuid_str=None, fs_label=None):
        """Format this partition with a filesystem.

        :param fstype: String of the filesystem format to use, defaults to ext4
        :param uuid: String of the UUID to assign to the filesystem. One will be
                     generated if this is left as None
        """
        try:
            data = {'fstype': fstype}

            if uuid_str:
                data['uuid'] = str(uuid_str)
            else:
                data['uuid'] = str(uuid.uuid4())

            if fs_label is not None:
                data['label'] = fs_label

            url = self.interpolate_url()

            self.logger.debug(
                "Formatting device %s on node %s as filesystem: %s" %
                (self.name, self.system_id, data))
            resp = self.api_client.post(url, op='format', files=data)

            if not resp.ok:
                raise Exception(
                    "MAAS error: %s - %s" % (resp.status_code, resp.text))

            self.refresh()
        except Exception as ex:
            msg = "Error: format of device %s on node %s failed: %s" \
                  % (self.name, self.system_id, str(ex))
            self.logger.error(msg)
            raise errors.DriverError(msg) 
Example 45
Project: drydock   Author: airshipit   File: volumegroup.py    Apache License 2.0 5 votes vote down vote up
def create_lv(self, name=None, uuid_str=None, size=None):
        """Create a logical volume in this volume group.

        :param name: Name of the logical volume
        :param uuid_str: A UUID4-format string specifying the LV uuid. Will be generated if left as None
        :param size: The size of the logical volume
        """
        try:
            if name is None or size is None:
                raise Exception(
                    "Cannot create logical volume without specified name and size"
                )

            if uuid_str is None:
                uuid_str = str(uuid.uuid4())

            data = {'name': name, 'uuid': uuid_str, 'size': size}

            self.logger.debug("Creating logical volume %s in VG %s on node %s"
                              % (name, self.name, self.system_id))

            url = self.interpolate_url()

            resp = self.api_client.post(
                url, op='create_logical_volume', files=data)

            if not resp.ok:
                raise Exception(
                    "MAAS error - %s - %s" % (resp.status_code, resp.txt))

            res = resp.json()
            if 'id' in res:
                return res['id']

        except Exception as ex:
            msg = "Error: Could not create logical volume: %s" % str(ex)
            self.logger.error(msg)
            raise errors.DriverError(msg) 
Example 46
Project: drydock   Author: airshipit   File: test_postgres_builddata.py    Apache License 2.0 5 votes vote down vote up
def test_build_data_insert_no_collected_date(self, blank_state):
        """Test that build data can be inserted omitting collection date."""
        build_data_fields = {
            'node_name': 'foo',
            'generator': 'hello_world',
            'data_format': 'text/plain',
            'data_element': 'Hello World!',
            'task_id': uuid.uuid4(),
        }

        build_data = objects.BuildData(**build_data_fields)

        result = blank_state.post_build_data(build_data)

        assert result 
Example 47
Project: drydock   Author: airshipit   File: test_postgres_builddata.py    Apache License 2.0 5 votes vote down vote up
def test_build_data_select_latest(self, blank_state):
        """Test that build data can be selected for only latest instance."""
        build_data_latest = {
            'node_name': 'foo',
            'generator': 'hello_world',
            'data_format': 'text/plain',
            'data_element': 'Hello World!',
            'task_id': uuid.uuid4(),
            'collected_date': datetime.utcnow(),
        }

        build_data_old = copy.deepcopy(build_data_latest)
        build_data_old['collected_date'] = build_data_latest[
            'collected_date'] - timedelta(days=1)
        build_data_old['task_id'] = uuid.uuid4()

        build_data1 = objects.BuildData(**build_data_latest)
        build_data2 = objects.BuildData(**build_data_old)

        result = blank_state.post_build_data(build_data1)

        assert result

        result = blank_state.post_build_data(build_data2)

        assert result

        bd_list = blank_state.get_build_data(node_name='foo', latest=True)

        assert len(bd_list) == 1

        assert bd_list[0].to_dict() == build_data1.to_dict() 
Example 48
Project: drydock   Author: airshipit   File: test_postgres_tasks.py    Apache License 2.0 5 votes vote down vote up
def test_task_insert(self, blank_state):
        """Test that a task can be inserted into the database."""
        ctx = DrydockRequestContext()
        ctx.user = 'sh8121'
        ctx.external_marker = str(uuid.uuid4())

        task = objects.Task(
            action='deploy_node',
            design_ref='http://foo.bar/design',
            context=ctx)

        result = blank_state.post_task(task)

        assert result 
Example 49
Project: drydock   Author: airshipit   File: test_postgres_tasks.py    Apache License 2.0 5 votes vote down vote up
def task_task_node_filter(self, blank_state):
        """Test that a persisted task persists node filter."""
        ctx = DrydockRequestContext()
        ctx.user = 'sh8121'
        ctx.external_marker = str(uuid.uuid4())

        node_filter = {
            'filter_set_type': 'union',
            'filter_set': [{
                'node_names': ['foo'],
                'filter_type': 'union'
            }]
        }
        task = objects.Task(
            action='deploy_node',
            node_filter=node_filter,
            design_ref='http://foo.bar/design',
            context=ctx)

        result = blank_state.post_task(task)

        assert result

        saved_task = blank_state.get_task(task.get_id())

        assert saved_task.node_filter == node_filter 
Example 50
Project: drydock   Author: airshipit   File: test_policy_engine.py    Apache License 2.0 5 votes vote down vote up
def test_authorize_context(self, mocker):
        ''' DrydockPolicy.authorized() should correctly use oslo_policy to enforce
            RBAC policy based on a DrydockRequestContext instance
        '''

        mocker.patch('oslo_policy.policy.Enforcer')
        ctx = DrydockRequestContext()

        # Configure context
        project_id = str(uuid.uuid4().hex)
        ctx.project_id = project_id
        user_id = str(uuid.uuid4().hex)
        ctx.user_id = user_id
        ctx.roles = ['admin']

        # Define action
        policy_action = 'physical_provisioner:read_task'

        policy_engine = DrydockPolicy()
        policy_engine.authorize(policy_action, ctx)

        expected_calls = [
            mocker.call.authorize(policy_action, {
                'project_id': project_id,
                'user_id': user_id
            }, ctx.to_policy_view())
        ]

        policy_engine.enforcer.assert_has_calls(expected_calls) 
Example 51
Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_9.py    MIT License 5 votes vote down vote up
def background(f):
    """Decorator that runs the wrapped function as a background task. It is
    assumed that this function creates a new resource, and takes a long time
    to do so. The response has status code 202 Accepted and includes a Location
    header with the URL of a task resource. Sending a GET request to the task
    will continue to return 202 for as long as the task is running. When the task
    has finished, a status code 303 See Other will be returned, along with a
    Location header that points to the newly created resource. The client then
    needs to send a DELETE request to the task resource to remove it from the
    system."""
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        # The background task needs to be decorated with Flask's
        # copy_current_request_context to have access to context globals.
        @copy_current_request_context
        def task():
            global background_tasks
            try:
                # invoke the wrapped function and record the returned
                # response in the background_tasks dictionary
                background_tasks[id] = make_response(f(*args, **kwargs))
            except:
                # the wrapped function raised an exception, return a 500
                # response
                background_tasks[id] = make_response(internal_server_error())

        # store the background task under a randomly generated identifier
        # and start it
        global background_tasks
        id = uuid.uuid4().hex
        background_tasks[id] = Thread(target=task)
        background_tasks[id].start()

        # return a 202 Accepted response with the location of the task status
        # resource
        return jsonify({}), 202, {'Location': url_for('get_task_status', id=id)}
    return wrapped

# g is the context request object from Flask 
Example 52
Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_8.py    MIT License 5 votes vote down vote up
def background(f):
    """Decorator that runs the wrapped function as a background task. It is
    assumed that this function creates a new resource, and takes a long time
    to do so. The response has status code 202 Accepted and includes a Location
    header with the URL of a task resource. Sending a GET request to the task
    will continue to return 202 for as long as the task is running. When the task
    has finished, a status code 303 See Other will be returned, along with a
    Location header that points to the newly created resource. The client then
    needs to send a DELETE request to the task resource to remove it from the
    system."""
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        # The background task needs to be decorated with Flask's
        # copy_current_request_context to have access to context globals.
        @copy_current_request_context
        def task():
            global background_tasks
            try:
                # invoke the wrapped function and record the returned
                # response in the background_tasks dictionary
                background_tasks[id] = make_response(f(*args, **kwargs))
            except:
                # the wrapped function raised an exception, return a 500
                # response
                background_tasks[id] = make_response(internal_server_error())

        # store the background task under a randomly generated identifier
        # and start it
        global background_tasks
        id = uuid.uuid4().hex
        background_tasks[id] = Thread(target=task)
        background_tasks[id].start()

        # return a 202 Accepted response with the location of the task status
        # resource
        return jsonify({}), 202, {'Location': url_for('get_task_status', id=id)}
    return wrapped 
Example 53
Project: Collaborative-Learning-for-Weakly-Supervised-Object-Detection   Author: Sunarker   File: pascal_voc.py    MIT License 5 votes vote down vote up
def __init__(self, image_set, year, use_diff=False):
    name = 'voc_' + year + '_' + image_set
    if use_diff:
      name += '_diff'
    imdb.__init__(self, name)
    self._year = year
    self._image_set = image_set
    self._devkit_path = self._get_default_path()
    self._data_path = os.path.join(self._devkit_path, 'VOC' + self._year)
    self._classes = (  # always index 0
                     'aeroplane', 'bicycle', 'bird', 'boat',
                     'bottle', 'bus', 'car', 'cat', 'chair',
                     'cow', 'diningtable', 'dog', 'horse',
                     'motorbike', 'person', 'pottedplant',
                     'sheep', 'sofa', 'train', 'tvmonitor')
    self._class_to_ind = dict(list(zip(self.classes, list(range(self.num_classes)))))
    self._image_ext = '.jpg'
    self._image_index = self._load_image_set_index()
    # Default to roidb handler
    self._roidb_handler = self.selective_search_roidb
    self._salt = str(uuid.uuid4())
    self._comp_id = 'comp4'

    # PASCAL specific config options
    self.config = {'cleanup': True,
                   'use_salt': True,
                   'use_diff': use_diff,
                   'matlab_eval': False,
                   'rpn_file': None}

    assert os.path.exists(self._devkit_path), \
      'VOCdevkit path does not exist: {}'.format(self._devkit_path)
    assert os.path.exists(self._data_path), \
      'Path does not exist: {}'.format(self._data_path) 
Example 54
Project: Collaborative-Learning-for-Weakly-Supervised-Object-Detection   Author: Sunarker   File: coco.py    MIT License 5 votes vote down vote up
def evaluate_detections(self, all_boxes, output_dir):
    res_file = osp.join(output_dir, ('detections_' +
                                     self._image_set +
                                     self._year +
                                     '_results'))
    if self.config['use_salt']:
      res_file += '_{}'.format(str(uuid.uuid4()))
    res_file += '.json'
    self._write_coco_results_file(all_boxes, res_file)
    # Only do evaluation on non-test sets
    if self._image_set.find('test') == -1:
      self._do_detection_eval(res_file, output_dir)
    # Optionally cleanup results json file
    if self.config['cleanup']:
      os.remove(res_file) 
Example 55
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: basic.py    Apache License 2.0 5 votes vote down vote up
def test_session_special_types(self):
        app = flask.Flask(__name__)
        app.secret_key = 'development-key'
        app.testing = True
        now = datetime.utcnow().replace(microsecond=0)
        the_uuid = uuid.uuid4()

        @app.after_request
        def modify_session(response):
            flask.session['m'] = flask.Markup('Hello!')
            flask.session['u'] = the_uuid
            flask.session['dt'] = now
            flask.session['t'] = (1, 2, 3)
            return response

        @app.route('/')
        def dump_session_contents():
            return pickle.dumps(dict(flask.session))

        c = app.test_client()
        c.get('/')
        rv = pickle.loads(c.get('/').data)
        self.assert_equal(rv['m'], flask.Markup('Hello!'))
        self.assert_equal(type(rv['m']), flask.Markup)
        self.assert_equal(rv['dt'], now)
        self.assert_equal(rv['u'], the_uuid)
        self.assert_equal(rv['t'], (1, 2, 3)) 
Example 56
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: basic.py    Apache License 2.0 5 votes vote down vote up
def test_session_special_types(self):
        app = flask.Flask(__name__)
        app.secret_key = 'development-key'
        app.testing = True
        now = datetime.utcnow().replace(microsecond=0)
        the_uuid = uuid.uuid4()

        @app.after_request
        def modify_session(response):
            flask.session['m'] = flask.Markup('Hello!')
            flask.session['u'] = the_uuid
            flask.session['dt'] = now
            flask.session['t'] = (1, 2, 3)
            return response

        @app.route('/')
        def dump_session_contents():
            return pickle.dumps(dict(flask.session))

        c = app.test_client()
        c.get('/')
        rv = pickle.loads(c.get('/').data)
        self.assert_equal(rv['m'], flask.Markup('Hello!'))
        self.assert_equal(type(rv['m']), flask.Markup)
        self.assert_equal(rv['dt'], now)
        self.assert_equal(rv['u'], the_uuid)
        self.assert_equal(rv['t'], (1, 2, 3)) 
Example 57
Project: dnsbin   Author: thomas-maurice   File: paste.py    Do What The F*ck You Want To Public License 5 votes vote down vote up
def on_post(self, req, resp):
        update = dns.update.Update(
            CONFIG.get('server', 'zone'),
            keyring=KEYRING,
            keyalgorithm=CONFIG.get('key', 'algo')
        )

        body = req.context['json']['data']
        LOGGER.info("Received %d byte long paste" % len(body))
        try:
            base64.b64decode(body.decode("ascii"))
        except Exception:
            raise falcon.HTTPBadRequest("Wrong encoding", "Your data is not base64 encoded !")

        uid = str(uuid.uuid4())
        i = 0
        for chunk in chunks(body, 255):
            i += 1
            LOGGER.info("Registering chunk %d of paste %s : %s" % (i, uid, chunk))
            update.replace("%d.%s" % (i, uid), 10, 'TXT', str(chunk))
            response = dns.query.tcp(update, CONFIG.get('server', 'address'))
        LOGGER.info("Registering chunk number of paste %s" % uid)
        update.replace("%s" % uid, 10, 'TXT', "%d" % i)
        response = dns.query.tcp(update, CONFIG.get('server', 'address'))
        req.context['result'] = {"paste": uid}
        LOGGER.info("Paste %s registered !" % uid) 
Example 58
Project: pypette   Author: csurfer   File: pipes.py    MIT License 5 votes vote down vote up
def _add_in_parallel(self, jobs):
        """Method to add jobs to pipeline so that they run in parallel.

        :param jobs: List of jobs submitted.
        :type jobs: list
        """
        self.job_map[uuid4()] = jobs
        logging.debug("{} submitted to be run in parallel".format(jobs)) 
Example 59
Project: pypette   Author: csurfer   File: pipes.py    MIT License 5 votes vote down vote up
def _add_in_series(self, jobs):
        """Method to add jobs to pipeline so that they run one after another,
        only after the previous job completes.

        :param jobs: List of jobs submitted.
        :type jobs: list
        """
        for job in jobs:
            self.job_map[uuid4()] = [job]
            logging.debug("{} submitted to be run in series".format(job)) 
Example 60
Project: everyclass-server   Author: everyclass   File: dao.py    Mozilla Public License 2.0 5 votes vote down vote up
def new_register_request(cls, sid_orig: str, verification_method: str, status: str,
                             password: str = None) -> str:
        """
        新增一条注册请求

        :param sid_orig: original sid
        :param verification_method: password or email
        :param status: status of the request
        :param password: if register by password, fill everyclass password here
        :return: the `request_id`
        """
        if verification_method not in ("email", "password"):
            raise ValueError("verification_method must be one of email, password")

        request_id = uuid.uuid4()

        with pg_conn_context() as conn, conn.cursor() as cursor:
            extra_doc = {}
            if password:
                extra_doc.update({"password": generate_password_hash(password)})

            insert_query = """
            INSERT INTO identity_verify_requests (request_id, identifier, method, status, create_time, extra)
                VALUES (%s,%s,%s,%s,%s,%s)
            """
            cursor.execute(insert_query, (request_id,
                                          sid_orig,
                                          verification_method,
                                          status,
                                          datetime.datetime.now(),
                                          extra_doc))
            conn.commit()

        return str(request_id) 
Example 61
Project: slidoc   Author: mitotic   File: sdproxy.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, sheetUpdateInfo, json_data, modRequests, synchronous=False):
        self.sheetUpdateInfo = sheetUpdateInfo
        self.json_data = json_data
        self.modRequests = modRequests
        self.synchronous = synchronous

        user = ADMINUSER_ID
        userToken = gen_proxy_token(user, ADMIN_ROLE)

        self.requestId = sliauth.iso_date(nosubsec=True)+'-'+uuid.uuid4().hex[:8]

        post_data = { 'proxy': '1', 'allupdates': '1', 'admin': user, 'token': userToken,
                      'data':  self.json_data}
        post_data['create'] = 'proxy'
        post_data['requestid'] = self.requestId
        if Global.updatePartial:
            post_data['partialrows'] = '1'
        if Settings['log_call']:
            post_data['logcall'] = str(Settings['log_call'])

        self.body = urllib.urlencode(post_data)

        self.cacheRequestTime = 0
        self.httpRequest = None
        if self.synchronous:
            self.http_client = tornado.httpclient.HTTPClient()
        else:
            self.http_client = tornado.httpclient.AsyncHTTPClient()

        self.cacheRetryCount = 0
        self.cacheWaitTime = 0 
Example 62
Project: FasterRCNN_TF_Py3   Author: upojzsb   File: pascal_voc.py    MIT License 5 votes vote down vote up
def __init__(self, image_set, year, devkit_path=None):
        imdb.__init__(self, 'voc_' + year + '_' + image_set)
        self._year = year
        self._image_set = image_set
        self._devkit_path = self._get_default_path() if devkit_path is None \
            else devkit_path
        self._data_path = os.path.join(self._devkit_path, 'VOC' + self._year)
        self._classes = ('__background__',  # always index 0
                         'aeroplane', 'bicycle', 'bird', 'boat',
                         'bottle', 'bus', 'car', 'cat', 'chair',
                         'cow', 'diningtable', 'dog', 'horse',
                         'motorbike', 'person', 'pottedplant',
                         'sheep', 'sofa', 'train', 'tvmonitor')
        self._class_to_ind = dict(list(zip(self.classes, list(range(self.num_classes)))))
        self._image_ext = '.jpg'
        self._image_index = self._load_image_set_index()
        # Default to roidb handler
        self._roidb_handler = self.gt_roidb
        self._salt = str(uuid.uuid4())
        self._comp_id = 'comp4'

        # PASCAL specific config options
        self.config = {'cleanup': True,
                       'use_salt': True,
                       'use_diff': False,
                       'matlab_eval': False,
                       'rpn_file': None}

        assert os.path.exists(self._devkit_path), \
            'VOCdevkit path does not exist: {}'.format(self._devkit_path)
        assert os.path.exists(self._data_path), \
            'Path does not exist: {}'.format(self._data_path) 
Example 63
Project: FasterRCNN_TF_Py3   Author: upojzsb   File: coco.py    MIT License 5 votes vote down vote up
def evaluate_detections(self, all_boxes, output_dir):
        res_file = osp.join(output_dir, ('detections_' +
                                         self._image_set +
                                         self._year +
                                         '_results'))
        if self.config['use_salt']:
            res_file += '_{}'.format(str(uuid.uuid4()))
        res_file += '.json'
        self._write_coco_results_file(all_boxes, res_file)
        # Only do evaluation on non-test sets
        if self._image_set.find('test') == -1:
            self._do_detection_eval(res_file, output_dir)
        # Optionally cleanup results json file
        if self.config['cleanup']:
            os.remove(res_file) 
Example 64
Project: Rackfocus   Author: Antrikshy   File: run.py    MIT License 5 votes vote down vote up
def main():
    if len(sys.argv) != 3:
        show_help()
        sys.exit(1)

    working_dir = sys.argv[1] + '/rackfocus_{}'.format(uuid.uuid4().hex[:8])
    output_dir = sys.argv[2]

    compiler = Compiler(working_dir, output_dir)
    compiler.fetch_datasets()
    compiler.setup_database()
    compiler.write_database()
    compiler.close_database()
    compiler.cleanup_datasets() 
Example 65
Project: ups-utils   Author: Ricks-Lab   File: UPSmodule.py    GNU General Public License v3.0 5 votes vote down vote up
def check_ups_list(self, quiet=True):
        """Check the list of UPS for compatibility, accessibility, and responsiveness.
        :param quiet: flag to specify if method should print results or return quietly
        :type quiet: bool
        :return: None
        :rtype: None
        """
        daemon_cnt = 0
        ups_cnt = 0
        for k, v in self.ups_list.items():
            v['uuid'] = uuid4().hex
            v['accessible'] = False
            v['responsive'] = False
            v['mib_commands'] = None
            if self.check_ups_type(v['ups_type']):
                v['compatible'] = True
                if self.check_ip(v):
                    v['accessible'] = True
                    if self.check_snmp(v):
                        v['responsive'] = True
                        ups_cnt += 1
                        v['mib_commands'] = self.all_mib_cmds[v['ups_type']]
                if v['daemon']:
                    daemon_cnt += 1
                    self.active_ups = v
            else:
                v['compatible'] = False
                v['mib_commands'] = None
        if not quiet:
            print('config.json contains {} total UPSs and {} daemon UPS'.format(ups_cnt, daemon_cnt))
    # End of read and check the UPS list.

    # Methods to get, check, and list UPSs 
Example 66
Project: elasticsearch-orm   Author: mayankchutani   File: properties.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, default=None, **kwargs):
        if default is None:
            default = str(uuid.uuid4())
        super().__init__(default=default, **kwargs) 
Example 67
Project: elasticsearch-orm   Author: mayankchutani   File: properties.py    GNU General Public License v3.0 5 votes vote down vote up
def default_value(self):
        return self.default if self.has_default else str(uuid.uuid4()) 
Example 68
Project: reroils-data-legacy   Author: rero   File: api.py    GNU General Public License v2.0 5 votes vote down vote up
def create(cls, data, id_=None, delete_pid=True,
               dbcommit=False, reindex=False, **kwargs):
        """Create a new ils record."""
        assert cls.minter
        if delete_pid and data.get('pid'):
            del(data['pid'])
        if not id_:
            id_ = uuid4()
        cls.minter(id_, data)
        record = super(IlsRecord, cls).create(data=data, id_=id_, **kwargs)
        if dbcommit:
            record.dbcommit(reindex)
        return record 
Example 69
Project: reroils-data-legacy   Author: rero   File: api.py    GNU General Public License v2.0 5 votes vote down vote up
def create(cls, json, id=None):
        """Create a new Transaction record."""
        if not id:
            id = str(uuid4())
        record = cls(json)
        record.model = cls.modelcls(json=record, id=id)
        with db.session.begin_nested():
            db.session.add(record.model)
        return record 
Example 70
Project: reroils-data-legacy   Author: rero   File: api.py    GNU General Public License v2.0 5 votes vote down vote up
def create(cls, id_=None, **kwargs):
        """Create a valid holding."""
        return cls(id=id_ or kwargs.pop('id', str(uuid.uuid4())), **kwargs) 
Example 71
Project: reroils-data-legacy   Author: rero   File: api.py    GNU General Public License v2.0 5 votes vote down vote up
def request_item(self, **kwargs):
        """Request item for the user.

        Adds a request to *_circulation.holdings*.

        :param user: Invenio-Accounts user.
        :param request_datetime: Start date of the loan.
                                 Must be today or a future date.
        :param waitlist: If the desired dates are not available, the item will
                         be put on a waitlist.
        :param delivery: 'pickup' or 'mail'
        """
        id = str(uuid4())
        self.holdings.append(Holding.create(id=id, **kwargs))
        CircTransaction.create(self.build_data(-1, 'add_item_request'), id=id) 
Example 72
Project: reroils-data-legacy   Author: rero   File: test_locations_fetchers.py    GNU General Public License v2.0 5 votes vote down vote up
def test_location_id_fetcher(db):
    """Test location_id fetcher."""
    data = {}
    rec_uuid = uuid4()
    minted_pid = minter(rec_uuid, data)
    fetched_pid = fetcher(rec_uuid, data)

    assert minted_pid.pid_value == fetched_pid.pid_value
    assert fetched_pid.pid_type == fetched_pid.provider.pid_type
    assert fetched_pid.pid_type == 'loc' 
Example 73
Project: reroils-data-legacy   Author: rero   File: test_organisations_fetchers.py    GNU General Public License v2.0 5 votes vote down vote up
def test_organisation_id_fetcher(db):
    """Test organisation_id fetcher."""
    data = {}
    rec_uuid = uuid4()
    minted_pid = minter(rec_uuid, data)
    fetched_pid = fetcher(rec_uuid, data)

    assert minted_pid.pid_value == fetched_pid.pid_value
    assert fetched_pid.pid_type == fetched_pid.provider.pid_type
    assert fetched_pid.pid_type == 'org' 
Example 74
Project: reroils-data-legacy   Author: rero   File: test_documents_fetchers.py    GNU General Public License v2.0 5 votes vote down vote up
def test_document_id_fetcher(db):
    """Test document_id fetcher."""
    data = {}
    rec_uuid = uuid4()
    minted_pid = minter(rec_uuid, data)
    fetched_pid = fetcher(rec_uuid, data)

    assert minted_pid.pid_value == fetched_pid.pid_value
    assert fetched_pid.pid_type == fetched_pid.provider.pid_type
    assert fetched_pid.pid_type == 'doc' 
Example 75
Project: reroils-data-legacy   Author: rero   File: test_patrons_fetchers.py    GNU General Public License v2.0 5 votes vote down vote up
def test_patron_id_fetcher(db):
    """Test patron_id fetcher."""
    data = {}
    rec_uuid = uuid4()
    minted_pid = minter(rec_uuid, data)
    fetched_pid = fetcher(rec_uuid, data)

    assert minted_pid.pid_value == fetched_pid.pid_value
    assert fetched_pid.pid_type == fetched_pid.provider.pid_type
    assert fetched_pid.pid_type == 'ptrn' 
Example 76
Project: alfred-yubikey-otp   Author: robertoriv   File: notify.py    MIT License 4 votes vote down vote up
def install_notifier():
    """Extract ``Notify.app`` from the workflow to data directory.

    Changes the bundle ID of the installed app and gives it the
    workflow's icon.
    """
    archive = os.path.join(os.path.dirname(__file__), 'Notify.tgz')
    destdir = wf().datadir
    app_path = os.path.join(destdir, 'Notify.app')
    n = notifier_program()
    log().debug('installing Notify.app to %r ...', destdir)
    # z = zipfile.ZipFile(archive, 'r')
    # z.extractall(destdir)
    tgz = tarfile.open(archive, 'r:gz')
    tgz.extractall(destdir)
    assert os.path.exists(n), \
        'Notify.app could not be installed in %s' % destdir

    # Replace applet icon
    icon = notifier_icon_path()
    workflow_icon = wf().workflowfile('icon.png')
    if os.path.exists(icon):
        os.unlink(icon)

    png_to_icns(workflow_icon, icon)

    # Set file icon
    # PyObjC isn't available for 2.6, so this is 2.7 only. Actually,
    # none of this code will "work" on pre-10.8 systems. Let it run
    # until I figure out a better way of excluding this module
    # from coverage in py2.6.
    if sys.version_info >= (2, 7):  # pragma: no cover
        from AppKit import NSWorkspace, NSImage

        ws = NSWorkspace.sharedWorkspace()
        img = NSImage.alloc().init()
        img.initWithContentsOfFile_(icon)
        ws.setIcon_forFile_options_(img, app_path, 0)

    # Change bundle ID of installed app
    ip_path = os.path.join(app_path, 'Contents/Info.plist')
    bundle_id = '{0}.{1}'.format(wf().bundleid, uuid.uuid4().hex)
    data = plistlib.readPlist(ip_path)
    log().debug('changing bundle ID to %r', bundle_id)
    data['CFBundleIdentifier'] = bundle_id
    plistlib.writePlist(data, ip_path) 
Example 77
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    MIT License 4 votes vote down vote up
def test_searching(self):
        """Test searching over collection elements."""
        for class_ in self.doc_collection_classes:
            target_property_1 = ""
            target_property_2 = ""
            for prop in self.doc.parsed_classes[class_]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink):
                    continue
                # Find nested object so we can test searching of elements by
                # properties of nested objects.
                if "vocab:" in prop.prop:
                    object_ = gen_dummy_object(class_, self.doc)
                    # Setting property of a nested object as target
                    for property_ in object_[prop.title]:
                        if property_ != "@type":
                            object_[prop.title][property_] = "target_1"
                            target_property_1 = "{}[{}]".format(prop.title, property_)
                            break
                    break
                elif target_property_1 is not "":
                    for property_ in object_:
                        if property_ != "@type":
                            object_[property_] = "target_2"
                            target_property_2 = property_
                            break
                    break

                if target_property_1 is not "" and target_property_2 is not "":
                    # Set search parameters
                    search_params = {
                        target_property_1: "target_1",
                        target_property_2: "target_2"
                    }

                    obj_id = str(uuid.uuid4())
                    response = crud.insert(object_=object_, id_=obj_id, session=self.session)
                    search_result = crud.get_collection(API_NAME="api", type_=class_,
                                                        session=self.session, paginate=True,
                                                        page_size=5, search_params=search_params)
                    assert len(search_result["members"]) > 0
                    search_item_id = search_result["members"][0]["@id"].split('/')[-1]
                    assert search_item_id == obj_id
                    break 
Example 78
Project: drydock   Author: airshipit   File: test_api_builddata.py    Apache License 2.0 4 votes vote down vote up
def seeded_builddata(self, blank_state):
        """Provide function to seed the database with build data."""

        def seed_build_data(nodelist=['foo'],
                            tasklist=None,
                            generatorlist=None,
                            count=1,
                            random_dates=True):
            """Seed the database with ``count`` build data elements for each node.

            If tasklist is specified, it should be a list of length ``count`` such that
            as build_data are added for a node, each task_id will be used one for each node

            :param nodelist: list of string nodenames for build data
            :param tasklist: list of uuid.UUID IDs for task. If omitted, uuids will be generated
            :param gneratorlist: list of string generatos to assign to build data. If omitted, 'hello_world'
                                 is used.
            :param count: number build data elements to create for each node
            :param random_dates: whether to generate random dates in the past 180 days or create each
                                 build data element with utcnow()
            """
            for n in nodelist:
                for i in range(count):
                    if random_dates:
                        collected_date = datetime.datetime.utcnow(
                        ) - datetime.timedelta(days=random.randint(1, 180))
                    else:
                        collected_date = None
                    if tasklist:
                        task_id = tasklist[i]
                    else:
                        task_id = uuid.uuid4()
                    if generatorlist:
                        generator = generatorlist[i]
                    else:
                        generator = 'hello_world'
                    bd = objects.BuildData(
                        node_name=n,
                        task_id=task_id,
                        generator=generator,
                        data_format='text/plain',
                        collected_date=collected_date,
                        data_element='Hello World!')
                    blank_state.post_build_data(bd)
                    i = i + 1

        return seed_build_data

    # TODO(sh8121att) Make this a general fixture in conftest.py 
Example 79
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: notify.py    MIT License 4 votes vote down vote up
def install_notifier():
    """Extract ``Notify.app`` from the workflow to data directory.

    Changes the bundle ID of the installed app and gives it the
    workflow's icon.
    """
    archive = os.path.join(os.path.dirname(__file__), 'Notify.tgz')
    destdir = wf().datadir
    app_path = os.path.join(destdir, 'Notify.app')
    n = notifier_program()
    log().debug('installing Notify.app to %r ...', destdir)
    # z = zipfile.ZipFile(archive, 'r')
    # z.extractall(destdir)
    tgz = tarfile.open(archive, 'r:gz')
    tgz.extractall(destdir)
    assert os.path.exists(n), \
        'Notify.app could not be installed in %s' % destdir

    # Replace applet icon
    icon = notifier_icon_path()
    workflow_icon = wf().workflowfile('icon.png')
    if os.path.exists(icon):
        os.unlink(icon)

    png_to_icns(workflow_icon, icon)

    # Set file icon
    # PyObjC isn't available for 2.6, so this is 2.7 only. Actually,
    # none of this code will "work" on pre-10.8 systems. Let it run
    # until I figure out a better way of excluding this module
    # from coverage in py2.6.
    if sys.version_info >= (2, 7):  # pragma: no cover
        from AppKit import NSWorkspace, NSImage

        ws = NSWorkspace.sharedWorkspace()
        img = NSImage.alloc().init()
        img.initWithContentsOfFile_(icon)
        ws.setIcon_forFile_options_(img, app_path, 0)

    # Change bundle ID of installed app
    ip_path = os.path.join(app_path, 'Contents/Info.plist')
    bundle_id = '{0}.{1}'.format(wf().bundleid, uuid.uuid4().hex)
    data = plistlib.readPlist(ip_path)
    log().debug('changing bundle ID to %r', bundle_id)
    data['CFBundleIdentifier'] = bundle_id
    plistlib.writePlist(data, ip_path) 
Example 80
Project: django-outlook-api   Author: spectrumone   File: outlookservice.py    MIT License 4 votes vote down vote up
def make_api_call(method, url, token, payload = None, parameters = None):
    # Send these headers with all API calls
    headers = { 'User-Agent' : 'django-tutorial/1.0',
                'Authorization' : 'Bearer {0}'.format(token),
                'Accept' : 'application/json'}

    # Use these headers to instrument calls. Makes it easier
    # to correlate requests and responses in case of problems
    # and is a recommended best practice.
    request_id = str(uuid.uuid4())
    instrumentation = { 'client-request-id' : request_id,
                        'return-client-request-id' : 'true' }

    headers.update(instrumentation)

    response = None 

    payload = {
              "Subject": "Discuss the Calendar REST API",
              "Body": {
                "ContentType": "HTML",
                "Content": "I think it will meet our requirements!"
              },
              "Start": {
                  "DateTime": "2014-04-04T18:00:00",
                  "TimeZone": "Pacific Standard Time"
              },
              "End": {
                  "DateTime": "2014-04-04T19:00:00",
                  "TimeZone": "Pacific Standard Time"
              },
              "Attendees": [
                {
                  "EmailAddress": {
                    "Address": "janets@a830edad9050849NDA1.onmicrosoft.com",
                    "Name": "Janet Schorr"
                  },
                  "Type": "Required"
                }
              ]
            }

    if (method.upper() == 'GET'):
        response = requests.get(url, headers = headers, params = parameters)
    elif (method.upper() == 'DELETE'):
        response = requests.delete(url, headers = headers, params = parameters)
    elif (method.upper() == 'PATCH'):
        headers.update({ 'Content-Type' : 'application/json' })
        response = requests.patch(url, headers = headers, data = json.dumps(payload), params = parameters)
    elif (method.upper() == 'POST'):
        headers.update({ 'Content-Type' : 'application/json' })
        response = requests.post(url, headers = headers, data = json.dumps(payload), params = parameters)

    return response