• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python transaction.abort函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: test_conflict_del_4

    def test_conflict_del_4(self):
        """Check conflict detection. We modify and delete the same object in
        different transactions, simulating separate processes."""
        foo = Foo('foo-first')
        self.dm.root['foo'] = foo

        transaction.commit()

        conn1 = testing.getConnection(testing.DBNAME)
        dm1 = datamanager.PJDataManager(conn1)
        conn2 = testing.getConnection(testing.DBNAME)
        dm2 = datamanager.PJDataManager(conn2)

        self.assertEqual(dm2.root['foo'].name, 'foo-first')
        del dm2.root['foo']

        self.assertEqual(dm1.root['foo'].name, 'foo-first')
        dm1.root['foo'].name = 'foo-second'

        #Finish in order 1 - 2
        # well, try to... dm1.tpc_finish will block until dm2 is done

        dm1.tpc_begin(None)
        dm2.tpc_begin(None)

        @testing.run_in_thread
        def background_commit():
            dm1.tpc_finish(None)
        with self.assertRaises(interfaces.ConflictError):
            dm2.tpc_finish(None)

        transaction.abort()

        conn2.close()
        conn1.close()
开发者ID:tonich-sh,项目名称:pjpersist,代码行数:35,代码来源:test_datamanager.py


示例2: populate_database

def populate_database():
    """Populate the database with some data useful for development."""
    if User.fetch_by(username='admin'):
        return

    # Admin user
    admin = User(name='Administrator', password='password',
                 username='admin', is_admin=True)
    # Class
    class_ = Class(name='CS32')
    Session.add(class_)
    Session.flush()

    # Project
    project = Project(name='Project 1', class_id=class_.id)
    Session.add(project)
    Session.flush()

    # File verification
    fv = FileVerifier(filename='test.c', min_size=3, min_lines=1,
                      project_id=project.id)

    Session.add_all([admin, fv])
    try:
        transaction.commit()
        print('Admin user created')
    except IntegrityError:
        transaction.abort()
开发者ID:ucsb-cs,项目名称:submit,代码行数:28,代码来源:models.py


示例3: prescanUpdate

    def prescanUpdate(self):
        """Update the factory's view of the world before each scan.

        For the basic BuilderFactory this means ending the transaction
        to ensure that data retrieved is up to date.
        """
        transaction.abort()
开发者ID:pombreda,项目名称:UnnaturalCodeFork,代码行数:7,代码来源:manager.py


示例4: tearDown

 def tearDown(self):
     try:
         transaction.abort()
     except AttributeError:
         # Zope 2.7
         get_transaction().abort()
     self.connection.close()
开发者ID:eaudeweb,项目名称:EionetProducts,代码行数:7,代码来源:testcase.py


示例5: _process

    def _process(self):
        room = self._reservation.room
        form = ModifyBookingForm(obj=self._reservation, old_start_date=self._reservation.start_dt.date())
        form.used_equipment.query = room.find_available_vc_equipment()

        if not room.notification_for_assistance and not self._reservation.needs_assistance:
            del form.needs_assistance

        if form.is_submitted() and not form.validate():
            occurrences = {}
            candidates = {}
            conflicts = {}
            pre_conflicts = {}
        else:
            occurrences, candidates = self._get_all_occurrences([room.id], form, reservation_id=self._reservation.id)
            conflicts, pre_conflicts = self._get_all_conflicts(room, form, self._reservation.id)

        if form.validate_on_submit() and not form.submit_check.data:
            try:
                self._reservation.modify(form.data, session.user)
                flash(_(u'Booking updated'), 'success')
            except NoReportError as e:
                transaction.abort()
                return jsonify(success=False, msg=unicode(e))
            return jsonify(success=True, url=self._get_success_url())

        return self._get_view(form=form, room=room, rooms=Room.find_all(), occurrences=occurrences,
                              candidates=candidates, conflicts=conflicts, pre_conflicts=pre_conflicts,
                              start_dt=form.start_dt.data, end_dt=form.end_dt.data, only_conflicts=False,
                              repeat_frequency=form.repeat_frequency.data, repeat_interval=form.repeat_interval.data,
                              reservation=self._reservation,
                              can_override=room.can_be_overridden(session.user)).display()
开发者ID:NIIF,项目名称:indico,代码行数:32,代码来源:reservations.py


示例6: initialize_sql

def initialize_sql(engine, admin_user=u'admin_user'):
    Base.metadata.bind = engine
    Base.metadata.create_all(engine)
    try:
        populate(admin_user)
    except IntegrityError:
        transaction.abort()
开发者ID:nyampire,项目名称:OSMTM,代码行数:7,代码来源:models.py


示例7: testThread

    def testThread(self):
        transaction.abort()
        global thread_error
        thread_error = None

        def target():
            try:
                session = Session()
                metadata.drop_all(engine)
                metadata.create_all(engine)

                query = session.query(User)
                rows = query.all()
                self.assertEqual(len(rows), 0)

                session.add(User(id=1, firstname='udo', lastname='juergens'))
                session.add(User(id=2, firstname='heino', lastname='n/a'))
                session.flush()

                rows = query.order_by(User.id).all()
                self.assertEqual(len(rows), 2)
                row1 = rows[0]
                d = row1.asDict()
                self.assertEqual(d, {'firstname': 'udo', 'lastname': 'juergens', 'id': 1})
            except Exception as err:
                global thread_error
                thread_error = err
            transaction.abort()

        thread = threading.Thread(target=target)
        thread.start()
        thread.join()
        if thread_error is not None:
            raise thread_error  # reraise in current thread
开发者ID:openvest,项目名称:zope.sqlalchemy,代码行数:34,代码来源:tests.py


示例8: checkMultipleUndoInOneTransaction

    def checkMultipleUndoInOneTransaction(self):
        # Verify that it's possible to perform multiple undo
        # operations within a transaction.  If ZODB performs the undo
        # operations in a nondeterministic order, this test will often
        # fail.

        conn = self._db.open()
        try:
            root = conn.root()

            # Add transactions that set root["state"] to (0..5)
            for state_num in range(6):
                transaction.begin()
                root['state'] = state_num
                transaction.get().note('root["state"] = %d' % state_num)
                transaction.commit()

            # Undo all but the first.  Note that no work is actually
            # performed yet.
            transaction.begin()
            log = self._db.undoLog()
            self._db.undoMultiple([log[i]['id'] for i in range(5)])

            transaction.get().note('undo states 1 through 5')

            # Now attempt all those undo operations.
            transaction.commit()

            # Sanity check: we should be back to the first state.
            self.assertEqual(root['state'], 0)
        finally:
            transaction.abort()
            conn.close()
开发者ID:agroszer,项目名称:ZODB,代码行数:33,代码来源:testZODB.py


示例9: abort_transaction

def abort_transaction():
    # FIXME: aborting a transaction means it could be commited later on. The
    # transaction should be doom()ed instead, but transaction.doom() is not
    # available on Zope 2.8. We should provide our own doom() implementation
    # which raises an exception on pre-commit-hook, which does exist
    # in Zope 2.8
    transaction.abort()
开发者ID:MarkTang,项目名称:erp5,代码行数:7,代码来源:Transaction.py


示例10: testAbortAfterCommit

 def testAbortAfterCommit(self):
     # This is a regression test which used to wedge the transaction
     # machinery when using PostgreSQL (and perhaps other) connections.
     # Basically, if a commit failed, there was no way to abort the
     # transaction. Leaving the transaction wedged.
     transaction.begin()
     session = Session()
     conn = session.connection()
     # At least PostgresSQL requires a rollback after invalid SQL is executed
     self.assertRaises(Exception, conn.execute, "BAD SQL SYNTAX")
     mark_changed(session)
     try:
         # Thus we could fail in commit
         transaction.commit()
     except:
         # But abort must succed (and actually rollback the base connection)
         transaction.abort()
         pass
     # Or the next transaction the next transaction will not be able to start!
     transaction.begin()
     session = Session()
     conn = session.connection()
     conn.execute("SELECT 1 FROM test_users")
     mark_changed(session)
     transaction.commit()
开发者ID:openvest,项目名称:zope.sqlalchemy,代码行数:25,代码来源:tests.py


示例11: editModule

def editModule(self, **kwargs):
      rme = self
      context = self.context
      response = self.request.RESPONSE
      # Perform the import
      try:
          payload = context.REQUEST['BODY']
          if payload:
            kwargs = {'original_file_name':'sword-import-file', 'user_name':getSecurityManager().getUser().getUserName()}
            text, subobjs, meta = doTransform(rme, "sword_to_folder", payload, meta=1, **kwargs)
            #context.plone_log("SWORD Import with id=%s: Transformed metadata and transformed document to cnxml." % (new_id))
            if text:
              rme.manage_delObjects([rme.default_file,])

              rme.invokeFactory('CNXML Document', rme.default_file, file=text, idprefix='zip-')
            makeContent(rme, subobjs)

            # Parse the returned mdml and set attributes up on the ModuleEditor object
            # Add any additional, unmatched, aka uncredited authors
            props = meta['properties']
            rme.updateProperties(props)
            # Make sure the metadata gets into the cnxml
            rme.editMetadata()

          #context.plone_log("SWORD Import with id=%s: Completed." % (new_id))
          response.setStatus('Created')
          return None#state.set(status='SwordImportSuccess', context=rme)

      except OOoImportError, e:
          transaction.abort()
          #context.plone_log("SWORD Import with id=%s: Aborted. There were problems transforming the openoffice or word document." % (new_id))
          message = context.translate("message_could_not_import", {"errormsg":e}, domain="rhaptos",
                                      default="Could not import file. %s" % e)
          response.setStatus('BadRequest')
          return None#state.set(status='SwordImportError', portal_status_message=message)
开发者ID:Rhaptos,项目名称:Products.RhaptosSword,代码行数:35,代码来源:atom.py


示例12: clear_snapshot

def clear_snapshot(signum=None, frame=None):
    global current_xmin_snapshot_id
    if current_xmin_snapshot_id is None:
        return
    transaction.abort()
    manager.pop()
    current_xmin_snapshot_id = None
开发者ID:ENCODE-DCC,项目名称:snovault,代码行数:7,代码来源:mpindexer.py


示例13: set_snapshot

def set_snapshot(xmin, snapshot_id):
    global current_xmin_snapshot_id
    if current_xmin_snapshot_id == (xmin, snapshot_id):
        return
    clear_snapshot()
    current_xmin_snapshot_id = (xmin, snapshot_id)

    while True:
        txn = transaction.begin()
        txn.doom()
        if snapshot_id is not None:
            txn.setExtendedInfo('snapshot_id', snapshot_id)
        session = app.registry[DBSESSION]()
        connection = session.connection()
        db_xmin = connection.execute(
            "SELECT txid_snapshot_xmin(txid_current_snapshot());").scalar()
        if db_xmin >= xmin:
            break
        transaction.abort()
        log.info('Waiting for xmin %r to reach %r', db_xmin, xmin)
        time.sleep(0.1)

    registry = app.registry
    request = app.request_factory.blank('/_indexing_pool')
    request.registry = registry
    request.datastore = 'database'
    apply_request_extensions(request)
    request.invoke_subrequest = app.invoke_subrequest
    request.root = app.root_factory(request)
    request._stats = {}
    manager.push({'request': request, 'registry': registry})
开发者ID:ENCODE-DCC,项目名称:snovault,代码行数:31,代码来源:mpindexer.py


示例14: __checkDatabase

 def __checkDatabase(self, db_name):
     db = self.neo.getSQLConnection(db_name)
     # wait for the sql transaction to be commited
     def callback(last_try):
         db.commit() # to get a fresh view
         # One revision per object and two for the root, before and after
         (object_number,), = db.query('SELECT count(*) FROM obj')
         return object_number == OBJECT_NUMBER + 2, object_number
     self.neo.expectCondition(callback)
     # no more temporarily objects
     (t_objects,), = db.query('SELECT count(*) FROM tobj')
     self.assertEqual(t_objects, 0)
     # One object more for the root
     query = 'SELECT count(*) FROM (SELECT * FROM obj GROUP BY oid) AS t'
     (objects,), = db.query(query)
     self.assertEqual(objects, OBJECT_NUMBER + 1)
     # Check object content
     db, conn = self.neo.getZODBConnection()
     root = conn.root()
     for i in xrange(OBJECT_NUMBER):
         obj = root[i]
         self.assertEqual(obj.value, i)
     transaction.abort()
     conn.close()
     db.close()
开发者ID:Nexedi,项目名称:neoppod,代码行数:25,代码来源:testStorage.py


示例15: transformIterable

 def transformIterable(self, result, encoding):
     if IPromises(self.request):
         transaction.abort()  # apparently safe in IPubBeforeCommitEvent
         return PromiseWorkerStreamIterator(
             IPromises(self.request), self.request, self.request.response)
     else:
         return None
开发者ID:datakurre,项目名称:experimental.promises,代码行数:7,代码来源:transforms.py


示例16: _teardown_db

def _teardown_db():
    import transaction
    transaction.abort()
    import sqlahelper
    sqlahelper.get_session().remove()
    from . import models as m
    m.Base.metadata.drop_all()
开发者ID:rebeccaframework,项目名称:shirly,代码行数:7,代码来源:tests.py


示例17: test_allocation_mode_unique_by_network_check_serialize_called

  def test_allocation_mode_unique_by_network_check_serialize_called(self):
    """
    Test that on being_requested serialise is being called
    code stolen from testERP5Security:test_MultiplePersonReferenceConcurrentTransaction
    """
    class DummyTestException(Exception):
      pass

    def verify_serialize_call(self):
      # it is checking that anything below computer_module raises exception
      # thanks to this this test do not have to be destructive
      if self.getPortalType() == "Hosting Subscription":
        raise DummyTestException
      else:
        return self.serialize_call()

    self._makeTree()
    self.software_instance.setSlaXml("""<?xml version='1.0' encoding='utf-8'?>
        <instance>
        <parameter id='mode'>unique_by_network</parameter>
        </instance>""")

    from Products.ERP5Type.Base import Base
    Base.serialize_call = Base.serialize
    try:
      Base.serialize = verify_serialize_call
      self.assertRaises(DummyTestException,
        self.software_instance.SoftwareInstance_tryToAllocatePartition)
    finally:
      Base.serialize = Base.serialize_call

    transaction.abort()
开发者ID:SlapOS,项目名称:slapos.core,代码行数:32,代码来源:test.erp5.testSlapOSCloudAllocationAlarm.py


示例18: _checkExpand

  def _checkExpand(self):
    """Check that expand() would not fail nor do major changes to the subobjects

    Transaction is aborted after 'expand' is called.

    See also SimulationTool._checkExpandAll
    """
    property_dict = {'Applied Rule': ('specialise',),
                     'Simulation Movement': ('delivery', 'quantity')}
    def fillRuleDict():
      rule_dict = {}
      object_list = deque((self,))
      while object_list:
        document = object_list.popleft()
        portal_type = document.getPortalType()
        document_dict = {'portal_type': portal_type}
        for property in property_dict[portal_type]:
          document_dict[property] = document.getProperty(property)
        rule_dict[document.getRelativeUrl()] = document_dict
        object_list += document.objectValues()
      return rule_dict
    initial_rule_dict = fillRuleDict()
    try:
      self.expand("immediate")
    except ConflictError:
      raise
    except Exception:
      msg = ''.join(ExceptionFormatter.format_exception(*sys.exc_info())[1:])
    else:
      final_rule_dict = fillRuleDict()
      msg = "%r != %r" % (initial_rule_dict, final_rule_dict) \
            if initial_rule_dict != final_rule_dict else None
    transaction.abort()
    return msg
开发者ID:Verde1705,项目名称:erp5,代码行数:34,代码来源:AppliedRule.py


示例19: open

    def open(self):
        import ZODB
        from ZODB.FileStorage import FileStorage
        from zc.lockfile import LockError
        self.path = self.conf['rdf.store_conf']
        openstr = os.path.abspath(self.path)

        try:
            fs = FileStorage(openstr)
        except IOError:
            L.exception("Failed to create a FileStorage")
            raise ZODBSourceOpenFailError(openstr)
        except LockError:
            L.exception('Found database "{}" is locked when trying to open it. '
                    'The PID of this process: {}'.format(openstr, os.getpid()), exc_info=True)
            raise DatabaseConflict('Database ' + openstr + ' locked')

        self.zdb = ZODB.DB(fs, cache_size=1600)
        self.conn = self.zdb.open()
        root = self.conn.root()
        if 'rdflib' not in root:
            root['rdflib'] = ConjunctiveGraph('ZODB')
        self.graph = root['rdflib']
        try:
            transaction.commit()
        except Exception:
            # catch commit exception and close db.
            # otherwise db would stay open and follow up tests
            # will detect the db in error state
            L.exception('Forced to abort transaction on ZODB store opening', exc_info=True)
            transaction.abort()
        transaction.begin()
        self.graph.open(self.path)
开发者ID:openworm,项目名称:PyOpenWorm,代码行数:33,代码来源:data.py


示例20: setup_db

def setup_db():
    """Crée toutes les tables du modèle dans la BDD."""
    #tmpdir = tempfile.mkdtemp(prefix="tests-vigiconf-")
    #settings["database"]["sqlalchemy_url"] = "sqlite:///%s/vigilo.db" % tmpdir
    transaction.abort()

    # La vue GroupPath dépend de Group et GroupHierarchy.
    # SQLAlchemy ne peut pas détecter correctement la dépendance.
    # On crée le schéma en 2 fois pour contourner ce problème.
    # Idem pour la vue UserSupItem (6 dépendances).
    from vigilo.models.tables.grouppath import GroupPath
    from vigilo.models.tables.usersupitem import UserSupItem
    mapped_tables = metadata.tables.copy()
    del mapped_tables[GroupPath.__tablename__]
    del mapped_tables[UserSupItem.__tablename__]
    metadata.create_all(tables=mapped_tables.itervalues())
    metadata.create_all(tables=[GroupPath.__table__, UserSupItem.__table__])

    DBSession.add(StateName(statename=u'OK', order=1))
    DBSession.add(StateName(statename=u'UNKNOWN', order=2))
    DBSession.add(StateName(statename=u'WARNING', order=3))
    DBSession.add(StateName(statename=u'CRITICAL', order=4))
    DBSession.add(StateName(statename=u'UP', order=1))
    DBSession.add(StateName(statename=u'UNREACHABLE', order=2))
    DBSession.add(StateName(statename=u'DOWN', order=4))
    MapGroup(name=u'Root')
    DBSession.flush()
开发者ID:vigilo,项目名称:vigiconf,代码行数:27,代码来源:helpers.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python transaction.begin函数代码示例发布时间:2022-05-27
下一篇:
Python trans_utils.i18n函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap