sqlalchemy.orm.orm_exc.NoResultFound

Here are the examples of the python api sqlalchemy.orm.orm_exc.NoResultFound taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

39 Examples 7

Example 1

Project: sqlalchemy
Source File: test_baked.py
View license
    def test_one_no_result(self):
        User = self.classes.User

        bq = self.bakery(lambda s: s.query(User))
        bq += lambda q: q.filter(User.name == 'asdf')

        assert_raises_message(
            orm_exc.NoResultFound,
            "No row was found for one()",
            bq(Session()).one
        )

Example 2

Project: franklin
Source File: db_utils.py
View license
    def get(self, kind, attributes):
        '''It returns one attribute with the given attributes and kind

        If more than one row match with the unique attributes from the given
        ones an error will be raised.
        If some of the attributes of the non unique ones are changed they will
        be updated.
        '''
        #do any of the attributes to get an instance from a foreign key?
        attributes = self._resolve_foreign_keys(kind, attributes)
        try:
            return self.select_one(kind, attributes)
        except orm_exc.NoResultFound:
            return self.create(kind, attributes)

Example 3

Project: franklin
Source File: db_utils.py
View license
    def get(self, kind, attributes):
        '''It returns one attribute with the given attributes and kind

        If more than one row match with the unique attributes from the given
        ones an error will be raised.
        If some of the attributes of the non unique ones are changed they will
        be updated.
        '''
        #do any of the attributes to get an instance from a foreign key?
        attributes = self._resolve_foreign_keys(kind, attributes)
        try:
            return self.select_one(kind, attributes)
        except orm_exc.NoResultFound:
            return self.create(kind, attributes)

Example 4

Project: pwnableweb
Source File: views.py
View license
@app.route('/login', methods=['POST'])
def login():
  try:
    user = models.User.query.filter(
        models.User.username == flask.request.form['username'],
        models.User.password == flask.request.form['password']
        ).one()
    flask.session['user'] = user.uid
  except orm_exc.NoResultFound:
    flask.flash('Invalid username and/or password.', 'warning')
  return flask.redirect(flask.url_for('home'))

Example 5

Project: pwnableweb
Source File: views.py
View license
@app.route('/login', methods=['POST'])
def login():
  try:
    user = models.User.query.filter(
        models.User.username == flask.request.form['username'],
        models.User.password == flask.request.form['password']
        ).one()
    flask.session['user'] = user.uid
  except orm_exc.NoResultFound:
    flask.flash('Invalid username and/or password.', 'warning')
  return flask.redirect(flask.url_for('home'))

Example 6

Project: pwnableweb
Source File: views.py
View license
@app.route('/u/<username>')
def user_page(username):
  _check_login()
  # SQLi
  try:
    query = 'SELECT * FROM user WHERE (username=\'%s\')' % username
    user = models.User.query.from_statement(query).one()
  except (exc.OperationalError, orm_exc.NoResultFound):
    user = None
  if not user:
    flask.flash('No such user!', 'warning')
    return flask.make_response(_render_page('error.html'), 404)
  posts = user.posts.filter(models.Post.recipient_id == None)
  return _render_posts_page(posts, user_profile=user)

Example 7

Project: pwnableweb
Source File: views.py
View license
@app.route('/u/<username>')
def user_page(username):
  _check_login()
  # SQLi
  try:
    query = 'SELECT * FROM user WHERE (username=\'%s\')' % username
    user = models.User.query.from_statement(query).one()
  except (exc.OperationalError, orm_exc.NoResultFound):
    user = None
  if not user:
    flask.flash('No such user!', 'warning')
    return flask.make_response(_render_page('error.html'), 404)
  posts = user.posts.filter(models.Post.recipient_id == None)
  return _render_posts_page(posts, user_profile=user)

Example 8

Project: dragonflow
Source File: versionobjects_db.py
View license
def _update_db_version_row(session, obj_id):
    try:
        row = session.query(models.DFVersionObjects).filter_by(
                object_uuid=obj_id).one()
        new_version = row.version + 1
        if new_version == sys.maxsize:
            new_version = 0
        row.version = new_version
        session.merge(row)
        session.flush()
        return new_version
    except orm_exc.NoResultFound:
        LOG.warning(_LW('NoResultFound in Neutron DB when'
                        'update version for object_id:%(id)s'), {'id': obj_id})
        return _create_db_version_row(session, obj_id)

Example 9

Project: dragonflow
Source File: versionobjects_db.py
View license
def _delete_db_version_row(session, obj_id):
    try:
        row = session.query(models.DFVersionObjects).filter_by(
                object_uuid=obj_id).one()
        session.delete(row)
        session.flush()
    except orm_exc.NoResultFound:
        pass

Example 10

Project: networking-brocade
Source File: globals.py
View license
    def _lookup(self, context):
        q = context.session.query(models_v2.Network)
        q = q.filter_by(
            id=vyatta_config.VROUTER.management_network_id)
        try:
            value = q.one()
        except orm_exc.NoResultFound:
            raise v_exc.InvalidParameter(
                cause=_('Management network {0} specified in vRouter plugin '
                        'configuration file does not exist').format(
                    vyatta_config.VROUTER.management_network_id))
        return value

Example 11

Project: solum
Source File: app.py
View license
    @classmethod
    @sql.retry
    def update_and_save(cls, context, id_or_uuid, data):
        try:
            session = sql.SolumBase.get_session()
            with session.begin():
                query = session.query(cls).filter_by(id=id_or_uuid)
                obj = sql.filter_by_project(context, query).one()
                if obj._is_updatable():
                    obj.update(data)
                    session.merge(obj)
            return obj
        except orm_exc.NoResultFound:
            cls._raise_not_found(id_or_uuid)

Example 12

Project: solum
Source File: models.py
View license
    @classmethod
    def get_by_id(cls, context, item_id):
        try:
            session = SolumBase.get_session()
            result = session.query(cls).filter_by(id=item_id)
            return filter_by_project(context, result).one()
        except orm_exc.NoResultFound:
            cls._raise_not_found(item_id)

Example 13

Project: solum
Source File: models.py
View license
    @classmethod
    def get_by_uuid(cls, context, item_uuid):
        try:
            session = SolumBase.get_session()
            result = session.query(cls).filter_by(uuid=item_uuid)
            return filter_by_project(context, result).one()
        except orm_exc.NoResultFound:
            cls._raise_not_found(item_uuid)

Example 14

Project: solum
Source File: models.py
View license
    @classmethod  # Must be top most
    @retry
    def update_and_save(cls, context, id_or_uuid, data):
        is_uuid = uuidutils.is_uuid_like(id_or_uuid)
        try:
            session = SolumBase.get_session()
            with session.begin():
                if is_uuid:
                    query = session.query(cls).filter_by(uuid=id_or_uuid)
                else:
                    query = session.query(cls).filter_by(id=id_or_uuid)
                obj = filter_by_project(context, query).one()
                if obj._is_updatable():
                    obj.update(data)
                    session.merge(obj)
            return obj
        except orm_exc.NoResultFound:
            cls._raise_not_found(id_or_uuid)

Example 15

Project: solum
Source File: workflow.py
View license
    @classmethod
    def get_by_assembly_id(cls, assembly_id):
        try:
            session = sql.Base.get_session()
            result = session.query(Workflow)
            result = result.filter(Workflow.assembly == assembly_id)
            return result.one()
        except orm_exc.NoResultFound:
            cls._raise_not_found(assembly_id)

Example 16

Project: solum
Source File: workflow.py
View license
    @classmethod
    @sql.retry
    def update_and_save(cls, context, id_or_uuid, data):
        try:
            session = sql.SolumBase.get_session()
            with session.begin():
                query = session.query(cls).filter_by(id=id_or_uuid)
                obj = sql.filter_by_project(context, query).one()
                if obj._is_updatable():
                    obj.update(data)
                    session.merge(obj)
            return obj
        except orm_exc.NoResultFound:
            cls._raise_not_found(id_or_uuid)

Example 17

Project: solum
Source File: workflow.py
View license
    @classmethod
    @sql.retry
    def insert(cls, context, db_obj):
        try:
            ss = sql.Base.get_session()
            with ss.begin():
                s = text("select max(wf_id) as max_wf_id "
                         "from workflow where app_id like :app")
                res = ss.execute(s, params=dict(app=db_obj.app_id)).fetchone()
                if res.max_wf_id:
                    db_obj.wf_id = res.max_wf_id + 1
                else:
                    db_obj.wf_id = 1
                db_obj.create(context)
        except orm_exc.NoResultFound:
            cls._raise_not_found(db_obj.app_id)

Example 18

Project: tacker
Source File: common_services_db.py
View license
    @log.log
    def get_event(self, context, event_id, fields=None):
        try:
            events_db = self._get_by_id(context, Event, event_id)
        except orm_exc.NoResultFound:
            raise common_services.EventNotFoundException(evt_id=event_id)
        return self._make_event_dict(events_db, fields)

Example 19

Project: tacker
Source File: db_base.py
View license
    def _get_by_name(self, context, model, name):
        try:
            query = self._model_query(context, model)
            return query.filter(model.name == name).one()
        except orm_exc.NoResultFound:
            LOG.info(_("No result found for %(name)s in %(model)s table"),
                     {'name': name, 'model': model})

Example 20

Project: tacker
Source File: nfvo_db.py
View license
    def _get_resource(self, context, model, id):
        try:
            return self._get_by_id(context, model, id)
        except orm_exc.NoResultFound:
            if issubclass(model, Vim):
                raise nfvo.VimNotFoundException(vim_id=id)
            else:
                raise

Example 21

Project: tacker
Source File: nfvo_db.py
View license
    def _does_already_exist(self, context, vim):
        try:
            query = self._model_query(context, VimAuth)
            for v_auth in query.filter(VimAuth.auth_url == vim.get('auth_url')
                                       ).all():
                vim = self._get_by_id(context, Vim, v_auth.get('vim_id'))
                if vim.get('deleted_at') is None:
                    return True
        except orm_exc.NoResultFound:
            pass

        return False

Example 22

Project: tacker
Source File: nfvo_db.py
View license
    def update_vim_status(self, context, vim_id, status):
        with context.session.begin(subtransactions=True):
            try:
                vim_db = (self._model_query(context, Vim).filter(
                    Vim.id == vim_id).with_lockmode('update').one())
            except orm_exc.NoResultFound:
                    raise nfvo.VimNotFoundException(vim_id=vim_id)
            vim_db.update({'status': status,
                           'updated_at': timeutils.utcnow()})
        return self._make_vim_dict(vim_db)

Example 23

Project: tacker
Source File: nfvo_db.py
View license
    def _validate_default_vim(self, context, vim, vim_id=None):
        if not vim.get('is_default'):
            return True
        try:
            vim_db = self._get_default_vim(context)
        except orm_exc.NoResultFound:
            return True
        if vim_id == vim_db.id:
            return True
        raise nfvo.VimDefaultDuplicateException(vim_id=vim_db.id)

Example 24

Project: tacker
Source File: vnffg_db.py
View license
    def _get_vnffg_db(self, context, vnffg_id, current_statuses, new_status):
        try:
            vnffg_db = (
                self._model_query(context, Vnffg).
                filter(Vnffg.id == vnffg_id).
                filter(Vnffg.status.in_(current_statuses)).
                with_lockmode('update').one())
        except orm_exc.NoResultFound:
            raise nfvo.VnffgNotFoundException(vnffg_id=vnffg_id)
        if vnffg_db.status == constants.PENDING_UPDATE:
            raise nfvo.VnffgInUse(vnffg_id=vnffg_id)
        vnffg_db.update({'status': new_status})
        return vnffg_db

Example 25

Project: tacker
Source File: vnffg_db.py
View license
    def _get_nfp_db(self, context, nfp_id, current_statuses, new_status):
        try:
            nfp_db = (
                self._model_query(context, VnffgNfp).
                filter(VnffgNfp.id == nfp_id).
                filter(VnffgNfp.status.in_(current_statuses)).
                with_lockmode('update').one())
        except orm_exc.NoResultFound:
            raise nfvo.NfpNotFoundException(nfp_id=nfp_id)
        if nfp_db.status == constants.PENDING_UPDATE:
            raise nfvo.NfpInUse(nfp_id=nfp_id)
        nfp_db.update({'status': new_status})
        return nfp_db

Example 26

Project: tacker
Source File: vnffg_db.py
View license
    def _get_sfc_db(self, context, sfc_id, current_statuses, new_status):
        try:
            sfc_db = (
                self._model_query(context, VnffgChain).
                filter(VnffgChain.id == sfc_id).
                filter(VnffgChain.status.in_(current_statuses)).
                with_lockmode('update').one())
        except orm_exc.NoResultFound:
            raise nfvo.SfcNotFoundException(sfc_id=sfc_id)
        if sfc_db.status == constants.PENDING_UPDATE:
            raise nfvo.SfcInUse(sfc_id=sfc_id)
        sfc_db.update({'status': new_status})
        return sfc_db

Example 27

Project: tacker
Source File: vnffg_db.py
View license
    def _get_classifier_db(self, context, fc_id, current_statuses, new_status):
        try:
            fc_db = (
                self._model_query(context, VnffgClassifier).
                filter(VnffgClassifier.id == fc_id).
                filter(VnffgClassifier.status.in_(current_statuses)).
                with_lockmode('update').one())
        except orm_exc.NoResultFound:
            raise nfvo.ClassifierNotFoundException(fc_id=fc_id)
        if fc_db.status == constants.PENDING_UPDATE:
            raise nfvo.ClassifierInUse(fc_id=fc_id)
        fc_db.update({'status': new_status})
        return fc_db

Example 28

Project: tacker
Source File: vnffg_db.py
View license
    def _get_resource(self, context, model, res_id):
        try:
            return self._get_by_id(context, model, res_id)
        except orm_exc.NoResultFound:
            if issubclass(model, Vnffg):
                raise nfvo.VnffgNotFoundException(vnffg_id=res_id)
            elif issubclass(model, VnffgClassifier):
                raise nfvo.ClassifierNotFoundException(classifier_id=res_id)
            if issubclass(model, VnffgTemplate):
                raise nfvo.VnffgdNotFoundException(vnffgd_id=res_id)
            if issubclass(model, VnffgChain):
                raise nfvo.SfcNotFoundException(sfc_id=res_id)
            else:
                raise

Example 29

Project: tacker
Source File: vnfm_db.py
View license
    def _get_resource(self, context, model, id):
        try:
            return self._get_by_id(context, model, id)
        except orm_exc.NoResultFound:
            if issubclass(model, VNFD):
                raise vnfm.VNFDNotFound(vnfd_id=id)
            elif issubclass(model, ServiceType):
                raise vnfm.ServiceTypeNotFound(service_type_id=id)
            if issubclass(model, VNF):
                raise vnfm.VNFNotFound(vnf_id=id)
            else:
                raise

Example 30

Project: tacker
Source File: vnfm_db.py
View license
    def _get_vnf_db(self, context, vnf_id, current_statuses, new_status):
        try:
            vnf_db = (
                self._model_query(context, VNF).
                filter(VNF.id == vnf_id).
                filter(VNF.status.in_(current_statuses)).
                with_lockmode('update').one())
        except orm_exc.NoResultFound:
            raise vnfm.VNFNotFound(vnf_id=vnf_id)
        if vnf_db.status == constants.PENDING_UPDATE:
            raise vnfm.VNFInUse(vnf_id=vnf_id)
        vnf_db.update({'status': new_status})
        return vnf_db

Example 31

Project: tacker
Source File: test_vim_client.py
View license
    def test_get_vim_without_defined_default_vim(self):
        vimclient = vim_client.VimClient()
        service_plugins = mock.Mock()
        nfvo_plugin = mock.Mock()
        nfvo_plugin.get_default_vim.side_effect = \
            orm_exc.NoResultFound()
        service_plugins.get.return_value = nfvo_plugin
        with mock.patch.object(manager.TackerManager, 'get_service_plugins',
                               return_value=service_plugins):
            self.assertRaises(nfvo.VimDefaultNotDefined,
                              vimclient.get_vim, None)

Example 32

Project: pyramid_simpleauth
Source File: model.py
View license
def authenticate_allow_email(username_or_email, raw_password):
    """Get an authenticated user corresponding to the credentials provided.

      Setup::

          >>> from mock import Mock
          >>> from pyramid_simpleauth import model
          >>> _get_existing_user = model.get_existing_user
          >>> _pwd_context = model.pwd_context
          >>> model.pwd_context = Mock()
          >>> model.get_existing_user = Mock()
          >>> mock_user = Mock()

      If the username doesn't match, returns ``None``::

          >>> model.get_existing_user.return_value = None
          >>> authenticate('username', 'password')

      If the username does match but the passwords don't, returns ``None``::

          >>> model.get_existing_user.return_value = mock_user
          >>> model.pwd_context.verify.return_value = False
          >>> authenticate('username', 'password')

      If the username and the password matches, returns the user::

          >>> model.pwd_context.verify.return_value = True
          >>> authenticate('username', 'password') == mock_user
          True

      Teardown::

          >>> model.pwd_context = _pwd_context
          >>> model.get_existing_user = _get_existing_user

    """

    # Check if it's an email.
    if '@' in username_or_email:
        try:
            query = Email.query.filter_by(address=username_or_email)
            candidates = [x.user for x in query if x.user and x.user.password]
            for candidate in candidates:
                if pwd_context.verify(raw_password, candidate.password):
                    return candidate
        except orm_exc.NoResultFound:
            pass
        return None
    else:
        return authenticate(username_or_email, raw_password)

Example 33

Project: franklin
Source File: db_utils.py
View license
    def _resolve_foreign_keys(self, table, attributes):
        '''Given a table an a dict with the colnames and values it fixes all
        the foreign keys.
        '''
        new_attrs = {}
        for column, this_col_attributes in attributes.items():
            if isinstance(this_col_attributes, dict):
                #we have to get the instance associated with this dict?
                #we need to know the table and pointed by the foreign key
                #pylint: disable-msg=W0612
                referenced_table, col = self._get_foreign_key(table, column)
                #if we really have a foreign key in this colum (key)
                #we ask for the instance with the value as attributes
                if referenced_table is None:
                    msg  = 'A dict given for a column with no foreign key -> '
                    msg += 'table:%s column:%s dict:%s ' % \
                            (table, column, str(this_col_attributes))
                    raise ValueError(msg)
                try:
                    row_instance = self.select_one(referenced_table,
                                           attributes=this_col_attributes)
                    #from sqlalchemy.orm import exc as orm_exc
                except orm_exc.NoResultFound:
                    msg = 'Failed to select a row instance for:\n'
                    msg += '\ttable %s \n\tattributes: %s' % \
                                    (referenced_table, str(this_col_attributes))
                    raise ValueError(msg)
                #where is the table for the current kind defined in the
                #mapping definitions list?
                indx = self._table_index_in_mapping(table)
                rel_attr = \
                self._mapping_definitions[indx]['relations'][column]['rel_attr']
                new_attrs[rel_attr] = row_instance
            else:
                new_attrs[column] = this_col_attributes
        return new_attrs

Example 34

Project: franklin
Source File: db_utils.py
View license
    def _resolve_foreign_keys(self, table, attributes):
        '''Given a table an a dict with the colnames and values it fixes all
        the foreign keys.
        '''
        new_attrs = {}
        for column, this_col_attributes in attributes.items():
            if isinstance(this_col_attributes, dict):
                #we have to get the instance associated with this dict?
                #we need to know the table and pointed by the foreign key
                #pylint: disable-msg=W0612
                referenced_table, col = self._get_foreign_key(table, column)
                #if we really have a foreign key in this colum (key)
                #we ask for the instance with the value as attributes
                if referenced_table is None:
                    msg  = 'A dict given for a column with no foreign key -> '
                    msg += 'table:%s column:%s dict:%s ' % \
                            (table, column, str(this_col_attributes))
                    raise ValueError(msg)
                try:
                    row_instance = self.select_one(referenced_table,
                                           attributes=this_col_attributes)
                    #from sqlalchemy.orm import exc as orm_exc
                except orm_exc.NoResultFound:
                    msg = 'Failed to select a row instance for:\n'
                    msg += '\ttable %s \n\tattributes: %s' % \
                                    (referenced_table, str(this_col_attributes))
                    raise ValueError(msg)
                #where is the table for the current kind defined in the
                #mapping definitions list?
                indx = self._table_index_in_mapping(table)
                rel_attr = \
                self._mapping_definitions[indx]['relations'][column]['rel_attr']
                new_attrs[rel_attr] = row_instance
            else:
                new_attrs[column] = this_col_attributes
        return new_attrs

Example 35

Project: dragonflow
Source File: lockedobjects_db.py
View license
@oslo_db_api.wrap_db_retry(max_retries=LOCK_MAX_RETRIES,
                           retry_interval=LOCK_INIT_RETRY_INTERVAL,
                           inc_retry_interval=True,
                           max_retry_interval=LOCK_MAX_RETRY_INTERVAL,
                           retry_on_deadlock=True)
def _test_and_create_object(id):
    try:
        session = db_api.get_session()
        with session.begin():
            row = session.query(models.DFLockedObjects).filter_by(
                object_uuid=id).one()
            # test ttl
            if row.lock and timeutils.is_older_than(row.created_at,
                                       cfg.CONF.df.distributed_lock_ttl):
                # reset the lock if it is timeout
                LOG.warning(_LW('The lock for object %(id)s is reset '
                                'due to timeout.'), {'id': id})
                _lock_free_update(session, id, lock_state=True,
                                  session_id=row.session_id)
    except orm_exc.NoResultFound:
        try:
            session = db_api.get_session()
            with session.begin():
                _create_db_row(session, oid=id)
        except db_exc.DBDuplicateEntry:
            # the lock is concurrently created.
            pass

Example 36

View license
    def test_preexisting_pt(self):
        ptg = self.create_policy_target_group()['policy_target_group']
        pt = self.create_policy_target(
            policy_target_group_id=ptg['id'])['policy_target']
        self.assertTrue('proxy_gateway' in pt)
        self.assertTrue('group_default_gateway' in pt)

        # Forcefully delete the entry in the proxy table, and verify that it's
        # fixed by the subsequent GET
        admin_context = n_ctx.get_admin_context()
        mapping = admin_context.session.query(
            group_proxy_db.ProxyGatewayMapping).filter_by(
                policy_target_id=pt['id']).one()
        admin_context.session.delete(mapping)
        query = admin_context.session.query(
            group_proxy_db.ProxyGatewayMapping).filter_by(
                policy_target_id=pt['id'])
        self.assertRaises(orm_exc.NoResultFound, query.one)

        # Showing the object just ignores the extension
        pt = self.show_policy_target(pt['id'],
                                     expected_res_status=200)['policy_target']
        self.assertFalse('proxy_gateway' in pt)
        self.assertFalse('group_default_gateway' in pt)

        # Updating the object just ignores the extension
        pt = self.update_policy_target(
            pt['id'], name='somenewname',
            expected_res_status=200)['policy_target']
        self.assertEqual('somenewname', pt['name'])
        self.assertFalse('proxy_gateway' in pt)
        self.assertFalse('group_default_gateway' in pt)

Example 37

Project: solum
Source File: workflow.py
View license
    @classmethod
    @sql.retry
    def destroy(cls, app_id):
        # Delete relevant plan, assembly, component on workflow delete
        try:
            session = sql.Base.get_session()
            plan_id = None
            image_name = None
            with session.begin():
                wfs = session.query(cls).filter_by(app_id=app_id).all()
                for wf_obj in wfs:
                    asm = session.query(assembly.Assembly).filter_by(
                        id=wf_obj.assembly).one()
                    plan_id = asm.plan_id
                    image_name = asm.name
                    # delete component
                    session.query(component.Component).filter_by(
                        assembly_id=wf_obj.assembly).delete()
                    # delete assembly
                    session.query(assembly.Assembly).filter_by(
                        id=wf_obj.assembly).delete()

                # delete plan
                if not plan_id:
                    plan_id = app_id
                session.query(plan.Plan).filter_by(id=plan_id).delete()
                # delete workflows
                session.query(cls).filter_by(app_id=app_id).delete()
                # delete image
                if image_name:
                    session.query(image.Image).filter_by(
                        name=image_name).delete()
        except orm_exc.NoResultFound:
            cls._raise_not_found(app_id)

Example 38

Project: tacker
Source File: nfvo_db.py
View license
    def update_vim(self, context, vim_id, vim):
        self._validate_default_vim(context, vim, vim_id=vim_id)
        with context.session.begin(subtransactions=True):
            vim_cred = vim['auth_cred']
            vim_project = vim['vim_project']
            is_default = vim.get('is_default')
            vim_db = self._get_resource(context, Vim, vim_id)
            try:
                if is_default:
                    vim_db.update({'is_default': is_default})
                vim_auth_db = (self._model_query(context, VimAuth).filter(
                    VimAuth.vim_id == vim_id).with_lockmode('update').one())
            except orm_exc.NoResultFound:
                    raise nfvo.VimNotFoundException(vim_id=vim_id)
            vim_auth_db.update({'auth_cred': vim_cred, 'password':
                               vim_cred.pop('password'), 'vim_project':
                               vim_project})
            vim_db.update({'updated_at': timeutils.utcnow()})
            self._cos_db_plg.create_event(
                context, res_id=vim_db['id'],
                res_type=constants.RES_TYPE_VIM,
                res_state=vim_db['status'],
                evt_type=constants.RES_EVT_UPDATE,
                tstamp=vim_db[constants.RES_EVT_UPDATED_FLD])

        return self.get_vim(context, vim_id)

Example 39

Project: tacker
Source File: vnfm_db.py
View license
    def _mark_vnf_status(self, vnf_id, exclude_status, new_status):
        context = t_context.get_admin_context()
        with context.session.begin(subtransactions=True):
            try:
                vnf_db = (
                    self._model_query(context, VNF).
                    filter(VNF.id == vnf_id).
                    filter(~VNF.status.in_(exclude_status)).
                    with_lockmode('update').one())
            except orm_exc.NoResultFound:
                LOG.warning(_('no vnf found %s'), vnf_id)
                return False

            vnf_db.update({'status': new_status})
            self._cos_db_plg.create_event(
                context, res_id=vnf_id,
                res_type=constants.RES_TYPE_VNF,
                res_state=new_status,
                evt_type=constants.RES_EVT_MONITOR,
                tstamp=timeutils.utcnow())
        return True