def set_rollback():
if hasattr(transaction, 'set_rollback'):
if connection.settings_dict.get('ATOMIC_REQUESTS', False):
# If running in >=1.6 then mark a rollback as required,
# and allow it to be handled by Django.
if connection.in_atomic_block:
transaction.set_rollback(True)
elif transaction.is_managed():
# Otherwise handle it explicitly if in managed mode.
if transaction.is_dirty():
transaction.rollback()
transaction.leave_transaction_management()
else:
# transaction not managed
pass
python类rollback()的实例源码
def managed_transaction(func):
""" This decorator wraps a function so that all sql executions in the function are atomic
It's used instead of django.db.transaction.commit_on_success in cases where reporting exceptions is necessary
as commit_on_success swallows exceptions
"""
@wraps(func)
@transaction.commit_manually
def _inner(*args, **kwargs):
try:
ret = func(*args, **kwargs)
except Exception:
transaction.rollback()
raise
else:
transaction.commit()
return ret
return _inner
def set_rollback():
if hasattr(transaction, 'set_rollback'):
if connection.settings_dict.get('ATOMIC_REQUESTS', False):
# If running in >=1.6 then mark a rollback as required,
# and allow it to be handled by Django.
if connection.in_atomic_block:
transaction.set_rollback(True)
elif transaction.is_managed():
# Otherwise handle it explicitly if in managed mode.
if transaction.is_dirty():
transaction.rollback()
transaction.leave_transaction_management()
else:
# transaction not managed
pass
def parse(self, fqdn, message):
hit = find_one_in_many(message['message'], self.selectors.keys())
if hit:
h = self.get_host(fqdn)
if h is None:
return
fn = self.selectors[hit]
with transaction.commit_manually():
try:
fn(message['message'], h)
except Exception, e:
syslog_events_log.error("Failed to parse log line '%s' using handler %s: %s" % (message['message'], fn, e))
transaction.rollback()
else:
transaction.commit()
def process_response(selfself, request, response):
if transaction.is_managed():
if transaction.is_dirty():
successful = not isinstance(response, http.HttpApplicationError)
if successful:
transaction.commit()
else:
transaction.rollback()
transaction.leave_transaction_management()
return response
def set_rollback():
if hasattr(transaction, 'set_rollback'):
if connection.settings_dict.get('ATOMIC_REQUESTS', False):
# If running in >=1.6 then mark a rollback as required,
# and allow it to be handled by Django.
if connection.in_atomic_block:
transaction.set_rollback(True)
elif transaction.is_managed():
# Otherwise handle it explicitly if in managed mode.
if transaction.is_dirty():
transaction.rollback()
transaction.leave_transaction_management()
else:
# transaction not managed
pass
def set_rollback():
if hasattr(transaction, 'set_rollback'):
if connection.settings_dict.get('ATOMIC_REQUESTS', False):
# If running in >=1.6 then mark a rollback as required,
# and allow it to be handled by Django.
if connection.in_atomic_block:
transaction.set_rollback(True)
elif transaction.is_managed():
# Otherwise handle it explicitly if in managed mode.
if transaction.is_dirty():
transaction.rollback()
transaction.leave_transaction_management()
else:
# transaction not managed
pass
def test_unique_users(self):
"""
there should not be two users with the same user_type and user_id
"""
for auth_system, auth_system_module in AUTH_SYSTEMS.iteritems():
models.User.objects.create(user_type = auth_system, user_id = 'foobar', info={'name':'Foo Bar'})
def double_insert():
models.User.objects.create(user_type = auth_system, user_id = 'foobar', info={'name': 'Foo2 Bar'})
self.assertRaises(IntegrityError, double_insert)
transaction.rollback()
def publish_form(callback):
try:
return callback()
except (PyXFormError, XLSFormError) as e:
return {
'type': 'alert-error',
'text': unicode(e)
}
except IntegrityError as e:
transaction.rollback()
return {
'type': 'alert-error',
'text': _(u'Form with this id or SMS-keyword already exists.'),
}
except ValidationError as e:
# on clone invalid URL
return {
'type': 'alert-error',
'text': _(u'Invalid URL format.'),
}
except AttributeError as e:
# form.publish returned None, not sure why...
return {
'type': 'alert-error',
'text': unicode(e)
}
except ProcessTimedOut as e:
# catch timeout errors
return {
'type': 'alert-error',
'text': _(u'Form validation timeout, please try again.'),
}
except Exception as e:
transaction.rollback()
# error in the XLS file; show an error to the user
return {
'type': 'alert-error',
'text': unicode(e)
}
def create(body):
"""
Create a new preset
"""
try:
body['codename'] = body['name'].strip().lower().replace(' ', '_')
existing = TicketWorkflowPreset.objects.filter(
codename=body['codename'],
name=body['name']
).count()
if existing:
transaction.rollback()
raise BadRequest('Preset with same codename/name exists')
preset = TicketWorkflowPreset.objects.create(codename=body['codename'], name=body['name'])
except (AttributeError, FieldError, ValueError) as ex:
raise BadRequest(ex)
try:
preset.config = __get_preset_config(body)
except (AttributeError, KeyError, ObjectDoesNotExist, TypeError, ValueError):
raise BadRequest('Invalid or missing params in action')
if body.get('templates') is not None:
for template_id in body['templates']:
try:
template = MailTemplate.objects.get(id=template_id)
preset.templates.add(template)
except (AttributeError, KeyError, ObjectDoesNotExist, ValueError):
raise BadRequest('Invalid template id')
preset.roles.clear()
for role_codename in body['roles']:
try:
role = Role.objects.get(codename=role_codename)
preset.roles.add(role)
except (AttributeError, KeyError, ObjectDoesNotExist, ValueError):
raise BadRequest('Invalid role codename')
preset.save()
return {'message': 'Preset successfully updated'}
def create_instance(username, xml_file, media_files,
status=u'submitted_via_web', uuid=None,
date_created_override=None, request=None):
"""
I used to check if this file had been submitted already, I've
taken this out because it was too slow. Now we're going to create
a way for an admin to mark duplicate instances. This should
simplify things a bit.
Submission cases:
If there is a username and no uuid, submitting an old ODK form.
If there is a username and a uuid, submitting a new ODK form.
"""
try:
instance = None
submitted_by = request.user \
if request and request.user.is_authenticated() else None
if username:
username = username.lower()
xml = xml_file.read()
xform = get_xform_from_submission(xml, username, uuid)
check_submission_permissions(request, xform)
existing_instance_count = Instance.objects.filter(
xml=xml, xform__user=xform.user).count()
if existing_instance_count > 0:
existing_instance = Instance.objects.filter(
xml=xml, xform__user=xform.user)[0]
if not existing_instance.xform or\
existing_instance.xform.has_start_time:
# Ignore submission as a duplicate IFF
# * a submission's XForm collects start time
# * the submitted XML is an exact match with one that
# has already been submitted for that user.
raise DuplicateInstance()
# get new and depracated uuid's
new_uuid = get_uuid_from_xml(xml)
duplicate_instances = Instance.objects.filter(uuid=new_uuid)
if duplicate_instances:
for f in media_files:
Attachment.objects.get_or_create(
instance=duplicate_instances[0],
media_file=f, mimetype=f.content_type)
# ensure we have saved the extra attachments
transaction.commit()
raise DuplicateInstance()
instance = save_submission(xform, xml, media_files, new_uuid,
submitted_by, status, date_created_override)
# commit all changes
transaction.commit()
return instance
except Exception:
transaction.rollback()
raise