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)
python类abort()的实例源码
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 tearDown(self):
from .models.meta import Base
testing.tearDown()
transaction.abort()
Base.metadata.drop_all(self.engine)