我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用transaction.abort()。
def remove_link_to_daily(request): link_id = request.matchdict.get('id') link = Link.query.filter_by(id=link_id).first() daily_id = request.matchdict.get('did') daily = Daily.query.filter_by(id=daily_id).first() if not link: transaction.abort() return Response('There is no link with id: %s' % link_id, 500) if not daily: transaction.abort() return Response('There is no daily with id: %s' % daily_id, 500) if link in daily.links: daily.links.remove(link) request.session.flash( 'success: Output is removed from daily: %s '% daily.name ) return Response('Output is removed to daily: %s '% daily.name)
def get_task_reviews(request): """RESTful version of getting all reviews of a task """ logger.debug('get_task_reviews is running') task_id = request.matchdict.get('id', -1) #task = Task.query.filter(Task.id == task_id).first() # if not task: # transaction.abort() # return Response('There is no task with id: %s' % task_id, 500) where_conditions = """where "Review_Tasks".id = %(task_id)s""" % { 'task_id': task_id } return get_reviews(request, where_conditions)
def get_user_reviews_count(request): """RESTful version of getting all reviews of a task """ logger.debug('get_user_reviews_count is running') reviewer_id = request.matchdict.get('id', -1) reviewer = User.query.filter(User.id == reviewer_id).first() if not reviewer: transaction.abort() return Response('There is no user with id: %s' % reviewer_id, 500) where_conditions = """where "Reviews".reviewer_id = %(reviewer_id)s and "Reviews_Statuses".code ='NEW' """ % {'reviewer_id': reviewer_id} reviews = get_reviews(request, where_conditions) return len(reviews)
def get_project_reviews(request): """RESTful version of getting all reviews of a task """ logger.debug('get_project_reviews is running') project_id = request.matchdict.get('id', -1) project = Project.query.filter(Project.id == project_id).first() if not project: transaction.abort() return Response('There is no user with id: %s' % project_id, 500) where_conditions = 'where "Review_Tasks".project_id = %(project_id)s' %\ {'project_id': project_id} return get_reviews(request, where_conditions)
def get_project_reviews_count(request): """RESTful version of getting all reviews of a task """ logger.debug('get_project_reviews_count is running') project_id = request.matchdict.get('id', -1) # project = Project.query.filter(Project.id == project_id).first() # if not project: # transaction.abort() # return Response('There is no project with id: %s' % project_id, 500) where_conditions = """ where "Review_Tasks".project_id = %(project_id)s and "Reviews_Statuses".code = 'NEW' """ % {'project_id': project_id} reviews = get_reviews(request, where_conditions) return len(reviews)
def delete_budgetentry(request): """deletes the budgetentry """ budgetentry_id = request.params.get('id') budgetentry = BudgetEntry.query.filter_by(id=budgetentry_id).first() if not budgetentry: transaction.abort() return Response('There is no budgetentry with id: %s' % budgetentry_id, 500) if budgetentry.type.name == 'Calendar': transaction.abort() return Response('You can not delete CalenderBasedEntry', 500) delete_budgetentry_action(budgetentry)
def delete_good(request): """deletes the good with data from request """ logger.debug('***delete good method starts ***') good_id = request.params.get('id') good = Good.query.filter_by(id=good_id).first() if not good: transaction.abort() return Response('There is no good with id: %s' % good_id, 500) good_name = good.name try: DBSession.delete(good) transaction.commit() except Exception as e: transaction.abort() c = StdErrToHTMLConverter(e) transaction.abort() return Response(c.html(), 500) return Response('Successfully deleted good with name %s' % good_name)
def tearDown(self): """Calls `pyramid.testing.tearDown` and `transaction.abort`. Prior to calling these methods if any `clean_db` method is defined, it will be called. Do database clean ups there. """ try: __clean_db = self.__getattribute__('clean_db') if callable(__clean_db): with transaction.manager: __clean_db() except AttributeError: pass testing.tearDown() transaction.abort()
def createUser(username, password, fullname, email, role): """Create a new L{User}. @param username: A C{unicode} username for the user. @param password: A C{unicode} password in plain text for the user. The password will be hashed before being stored. @param fullname: A C{unicode} name for the user. @param email: The C{unicode} email address for the user. @param role: The L{Role} for the user. @return: A C{list} of C{(objectID, username)} 2-tuples for the new L{User}s. """ username = username.lower() users = UserAPI() result = users.create([(username, password, fullname, email)]) # Set the role with an update to ensure that the 'fluiddb/users/role' tag # value is set correctly. users.set([(username, None, None, None, role)]) try: transaction.commit() except: transaction.abort() raise return result
def updateUser(username, password, fullname, email, role): """Updates a L{User}. @param username: A C{unicode} username for the user. @param password: A C{unicode} password in plain text for the user. The password will be hashed before being stored. @param fullname: A C{unicode} name for the user. @param email: The C{unicode} email address for the user. @param role: The L{Role} for the user. @return: @return: A C{(objectID, username)} 2-tuple representing the L{User} that was updated. """ try: result = UserAPI().set([(username, password, fullname, email, role)]) transaction.commit() except: transaction.abort() raise return result
def setVersionTag(version): """Updates the fluiddb/version tag. @param version: The new version string. """ user = getUser(u'fluiddb') objectID = ObjectAPI(user).create(u'fluidinfo') releaseDate = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') values = {objectID: { u'fluiddb/api-version': { 'mime-type': 'text/plain', 'contents': version}, u'fluiddb/release-date': { 'mime-type': 'text/plain', 'contents': releaseDate + '\n'}}} TagValueAPI(user).set(values) PermissionAPI(user).set([ (u'fluiddb/api-version', Operation.READ_TAG_VALUE, Policy.OPEN, []), (u'fluiddb/release-date', Operation.READ_TAG_VALUE, Policy.OPEN, [])]) try: transaction.commit() except: transaction.abort() raise
def queue_domain_process(self): try: queue_results = lib_db.queue_domains__process(self.request.api_context) if self.request.matched_route.name == 'admin:queue_domains:process.json': return {'result': 'success', } return HTTPFound("%s/queue-domains?processed=1" % self.request.registry.settings['admin_prefix']) except (lib_errors.DisplayableError, lib_errors.DomainVerificationError) as e: # return, don't raise # we still commit the bookkeeping if self.request.matched_route.name == 'admin:queue_domains:process.json': return {'result': 'error', 'error': e.message, } return HTTPFound("%s/queue-domains?processed=0&error=%s" % (self.request.registry.settings['admin_prefix'], e.message)) except Exception as e: transaction.abort() if self.request.matched_route.name == 'admin:queue_domains:process.json': return {'result': 'error', 'error': e.message, } raise # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def queue_renewal_update(self): try: queue_results = lib_db.queue_renewals__update(self.request.api_context) if self.request.matched_route.name == 'admin:api:queue_renewals:update.json': return {'result': 'success', } return HTTPFound("%s/queue-renewals?update=1" % self.request.registry.settings['admin_prefix']) except Exception as e: transaction.abort() if self.request.matched_route.name == 'admin:api:queue_renewals:update.json': return {'result': 'error', 'error': e.message, } raise # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def process_oils(session_class): session = session_class() record_ids = [r.adios_oil_id for r in session.query(ImportedRecord)] session.close() logger.info('Adding Oil objects...') for record_id in record_ids: # Note: committing our transaction for every record slows the # import job significantly. But this is necessary if we # want the option of rejecting oil records. session = session_class() transaction.begin() rec = (session.query(ImportedRecord) .filter(ImportedRecord.adios_oil_id == record_id) .one()) try: add_oil(rec) transaction.commit() except OilRejected as e: logger.warning(repr(e)) transaction.abort()
def test_celery__TransactionAwareTask____call____1__cov( interaction, eager_celery_app): """It aborts the transaction in case of an error during task execution. As it is hard to collect coverage for subprocesses we use this test for coverage only. """ task_call = 'celery.Task.__call__' configure_zope = 'z3c.celery.celery.TransactionAwareTask.configure_zope' with mock.patch(configure_zope), \ mock.patch(task_call, side_effect=RuntimeError) as task_call, \ mock.patch('transaction.abort') as abort: zope.security.management.endInteraction() with pytest.raises(RuntimeError): # We want to simulate a run in worker. The RuntimeError is raised # by the mock eager_task(_run_asynchronously_=True) assert task_call.called assert abort.called
def test_celery__TransactionAwareTask____call____2__cov( interaction, eager_celery_app): """It aborts the transaction and retries in case of a ConflictError. As it is hard to collect coverage for sub-processes we use this test for coverage only. """ configure_zope = 'z3c.celery.celery.TransactionAwareTask.configure_zope' with mock.patch(configure_zope), \ mock.patch('transaction.abort', side_effect=transaction.abort) as abort, \ mock.patch('time.sleep') as sleep: zope.security.management.endInteraction() with pytest.raises(celery.exceptions.MaxRetriesExceededError): conflict_task(_run_asynchronously_=True) assert abort.called assert 2 == sleep.call_count # We have max_retries=1 for this task
def transaction(self, principal_id): if principal_id: transaction.begin() login_principal(get_principal(principal_id)) try: yield except: transaction.abort() raise else: try: transaction.commit() except ZODB.POSException.ConflictError: log.warning('Conflict while publishing', exc_info=True) transaction.abort() raise finally: zope.security.management.endInteraction()
def sqlengine(request): """Create an engine.""" config = testing.setUp(settings=TEST_DB_SETTINGS) config.include("..models") config.include("..routes") settings = config.get_settings() engine = get_engine(settings) Base.metadata.create_all(engine) def teardown(): testing.tearDown() transaction.abort() Base.metadata.drop_all(engine) request.addfinalizer(teardown) return engine
def get_client_users_out_stack(request): logger.debug('get_client_users_out_stack is running') client_id = request.matchdict.get('id', -1) client = Client.query.filter_by(id=client_id).first() if not client: transaction.abort() return Response('Can not find a client with id: %s' % client_id, 500) sql_query = """ select "User_SimpleEntities".name, "User_SimpleEntities".id from "Users" left outer join "Client_Users" on "Client_Users".uid = "Users".id join "SimpleEntities" as "User_SimpleEntities" on "User_SimpleEntities".id = "Users".id where "Client_Users".cid != %(client_id)s or "Client_Users".cid is Null """ sql_query = sql_query % {'client_id': client_id} result = DBSession.connection().execute(sql_query) users = [] for r in result.fetchall(): user = { 'name': r[0], 'id': r[1] } users.append(user) resp = Response( json_body=users ) return resp
def update_daily(request): """runs when updating a daily """ logged_in_user = get_logged_in_user(request) utc_now = local_to_utc(datetime.datetime.now()) daily_id = request.matchdict.get('id', -1) daily = Daily.query.filter(Daily.id == daily_id).first() if not daily: transaction.abort() return Response('No daily with id : %s' % daily_id, 500) name = request.params.get('name') description = request.params.get('description') status_id = request.params.get('status_id') status = Status.query.filter(Status.id == status_id).first() if not name: return Response('Please supply a name', 500) if not description: return Response('Please supply a description', 500) if not status: return Response('There is no status with code: %s' % status.code, 500) daily.name = name daily.description = description daily.status = status daily.date_updated = utc_now daily.updated_by = logged_in_user request.session.flash('success: Successfully updated daily') return Response('Successfully updated daily')
def update_budget(request): """runs when updating a budget """ logged_in_user = get_logged_in_user(request) utc_now = local_to_utc(datetime.datetime.now()) budget_id = request.matchdict.get('id', -1) budget = Budget.query.filter(Budget.id == budget_id).first() if not budget: transaction.abort() return Response('No budget with id : %s' % budget_id, 500) name = request.params.get('name') description = request.params.get('description') status_id = request.params.get('status_id') status = Status.query.filter(Status.id == status_id).first() if not name: return Response('Please supply a name', 500) if not description: return Response('Please supply a description', 500) if not status: return Response('There is no status with code: %s' % status.code, 500) budget.name = name budget.description = description budget.status = status budget.date_updated = utc_now budget.updated_by = logged_in_user request.session.flash('success: Successfully updated budget') return Response('Successfully updated budget')
def delete_budgetentry_action(budgetentry): logger.debug('delete_budgetentry_action %s' % budgetentry.name) budgetentry_name = budgetentry.name try: DBSession.delete(budgetentry) transaction.commit() except Exception as e: transaction.abort() c = StdErrToHTMLConverter(e) transaction.abort() # return Response(c.html(), 500) # return Response('Successfully deleted good with name %s' % budgetentry_name)
def studio_scheduling_mode(request): """Sets the system to "in schedule" mode or "normal" mode. When the system is "in schedule" mode (Studio.is_scheduling == True) it is not allowed to schedule the system again until the previous one is finishes. """ logged_in_user = get_logged_in_user(request) # get the studio studio = Studio.query.first() mode = request.params.get('mode') logger.debug('schedule mode: %s' % mode) if not studio: transaction.abort() return Response("There is no Studio instance\n" "Please create a studio first", 500) if mode: # set the mode mode = bool(int(mode)) studio.is_scheduling = mode studio.is_scheduling_by = logged_in_user studio.scheduling_started_at = local_to_utc(datetime.datetime.now()) return Response( "Successfully, set the scheduling mode to: %s" % mode )
def server_error(exc, request): msg = exc.args[0] if exc.args else '' response = Response('Server Error: %s' % msg, 500) transaction.abort() return response
def start(self, context, request, appstruct, **kw): odtfile = io.BytesIO() try: if appstruct: schedules = appstruct['venues'] next_date = dates_to_fr_date(appstruct['next_date']) schedules_objs = [] for venue_data in schedules: venue = venue_data['title'] schedules_objs.extend(get_schedules( venue_data['schedules'], venue, next_date)) source_class = None classifications = (CLASSIFICATIONS['venue_classification'], CLASSIFICATIONS['city_classification']) for classification in classifications: source_class = classification(source_class) folder = generate_search_smart_folder('Extraction folder') folder.classifications = source_class odtfile = folder.classifications.extract( schedules_objs, request, folder, template_type="extraction") transaction.abort() except Exception as error: log.warning(error) return {'odtfile': odtfile}
def tearDown(self): from .models.meta import Base testing.tearDown() transaction.abort() Base.metadata.drop_all(self.engine)
def _error(self, message): """Print an error message and exit. @param message: The C{str} error message to print. """ print >> self.outf, message transaction.abort() sys.exit(1)
def deleteUser(username): """Delete a L{User}. @param username: A C{unicode} username for the user. """ result = UserAPI().delete([username]) try: transaction.commit() except: transaction.abort() raise return result
def patchDatabase(store, schema): """Create a schema or apply databases patches to a database. @param store: The C{Store} for the database. @param schema: The Storm C{Schema} for the database. """ try: schema.upgrade(store) except: transaction.abort() raise else: transaction.commit()
def transaction_middleware(get_response): """ Calls `transaction.abort()` before and after obtaining a response. """ def middleware(request): transaction.abort() response = get_response(request) transaction.abort() return response return middleware
def formatted_value(self): today_begin = timezone.now().replace(hour=0, minute=0, microsecond=0) jobs = 0 for job in NumberTree.reversed(data_root().jobs_by_state[Job.State.done]): if job.created < today_begin: break jobs += 1 transaction.abort() return str(jobs)
def queue_renewal_process(self): try: queue_results = lib_db.queue_renewals__process(self.request.api_context) if self.request.matched_route.name == 'admin:api:queue_renewals:process.json': return {'result': 'success', } return HTTPFound("%s/queue-renewals?process=1&results=%s" % (self.request.registry.settings['admin_prefix'], queue_results)) except Exception as e: transaction.abort() if self.request.matched_route.name == 'admin:api:queue_renewals:process.json': return {'result': 'error', 'error': e.message, } raise
def __exit__(self, exc_type, exc_value, exc_tb): if exc_type is None: transaction.commit() meta = self._root['meta'] if self.has_updates: meta.unpacked += 1 if meta.unpacked > 25: logger.debug('Packing database') self._db.pack() meta.unpacked = 0 transaction.commit() else: transaction.abort() self._connection.close()
def forbidden(request): # The template rendering opens a new transaction which is not rolled back by Pyramid transaction machinery, because we are in a very special view. This tranaction will cause the tests to hang as the open transaction blocks Base.drop_all() in PostgreSQL. Here we have careful instructions to roll back any pending transaction by hand. html = render('core/forbidden.html', {}, request=request) resp = Response(html) resp.status_code = 403 # Hint pyramid_redis_session not to generate any session cookies for this response resp.cache_control.public = True transaction.abort() return resp
def notfound(request): """Not found view which will log the 404s in the site error log.""" # Try to extract some more information from request user = getattr(request, "user", None) if user: username = getattr(user, "friendly_name", "<unknown>") else: username = "<anomymous>" # TODO: Maybe make this configurable, default to WARN, configurable as INFO for high volume sites logger.info("404 Not Found. user:%s URL:%s referrer:%s", request.url, username, request.referrer) # Make sure 404 page does not have any status information, as it is often overlooked special case for caching and we don't want to cache user information try: request.user = None except: # pyramid_tm 2.0 - this fails pass # The template rendering opens a new transaction which is not rolled back by Pyramid transaction machinery, because we are in a very special view. This tranaction will cause the tests to hang as the open transaction blocks Base.drop_all() in PostgreSQL. Here we have careful instructions to roll back any pending transaction by hand. html = render('core/notfound.html', {}, request=request) resp = Response(html) resp.status_code = 404 # Hint pyramid_redis_session not to generate any session cookies for this response resp.cache_control.public = True transaction.abort() return resp
def save_customer(self, data): try: customer = Customer(**data) self.db.add(customer) self.db.flush() self.db.refresh(customer) return customer except exc.SQLAlchemyError as e: # pragma: no cover transaction.abort() raise DatabaseFailure(str(e))
def abort(self, trans): pass
def except_with_handler(): """Raise an exception which is handled after abort.""" site = zope.component.hooks.getSite() site['foo'] = 'bar' def handler(arg1, arg2, kw1=1, kw2=2): interaction = zope.security.management.getInteraction() site['data'] = (arg1, arg2, kw1, kw2, interaction.participations[0].principal.title) raise HandleAfterAbort(handler, 'a1', 'a2', kw2=4)
def test_celery__TransactionAwareTask__run_in_worker__1( celery_session_worker, storage_file, interaction): """It handles specific exceptions in a new transaction after abort.""" job = except_with_handler.delay() transaction.commit() with pytest.raises(Exception): job.get() with open_zodb_copy(storage_file) as app: assert [('data', ('a1', 'a2', 1, 4, u'User'))] == list(app.items())
def test_celery__TransactionAwareTask__run_in_worker__2( celery_session_worker, storage_file, interaction): """It handles a specific exceptions to abort the transaction but still count as a successful job.""" job = success_but_abort_transaction.delay() transaction.commit() assert 'done' == job.get() with open_zodb_copy(storage_file) as app: assert 'flub' not in app
def run_in_same_process(self, args, kw): try: return super(TransactionAwareTask, self).__call__(*args, **kw) except Abort as handle: transaction.abort() handle() return handle.message except HandleAfterAbort as handle: handle() raise
def tearDown(self): testing.tearDown() transaction.abort()
def new_session(sqlengine, request): """Return a session.""" session_factory = get_session_factory(sqlengine) session = get_tm_session(session_factory, transaction.manager) def teardown(): transaction.abort() request.addfinalizer(teardown) return session
def tearDown(self): noSecurityManager() transaction.abort() self.app._p_jar.close()