本文整理汇总了Python中django.db.transaction.commit方法的典型用法代码示例。如果您正苦于以下问题:Python transaction.commit方法的具体用法?Python transaction.commit怎么用?Python transaction.commit使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.transaction
的用法示例。
在下文中一共展示了transaction.commit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: reopen_or_comment_alert
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def reopen_or_comment_alert( request, alert_type, alert_id, update_code, wording):
alert = get_object_or_404(Alert, id=alert_id, alerttype__unit__in=request.units)
if request.method == 'POST':
form = AlertUpdateForm(request.POST)
if form.is_valid():
f = form.save(commit=False)
f.alert = alert
f.update_type = update_code
f.save()
messages.success(request, "Updated alert %s." % str(alert) )
l = LogEntry(userid=request.user.username,
description="Updated alert %s." % str(alert),
related_object=form.instance)
l.save()
return HttpResponseRedirect(reverse('alerts.views.view_alert', kwargs={'alert_type':alert_type, 'alert_id':alert_id}))
else:
form = AlertUpdateForm()
return render(request, 'alerts/resolve_alert.html', { 'alert_type':alert.alerttype,
'alert':alert,
'form': form,
'resolve_reopen_or_comment_on': wording})
示例2: email_alert
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def email_alert( request, alert_type, alert_id ):
alert = get_object_or_404(Alert, id=alert_id, alerttype__unit__in=request.units)
if request.method == 'POST':
form = EmailResolutionForm(request.POST)
if form.is_valid():
f = form.save(commit=False)
f.alert = alert
f.update_type = "EMAI"
f.save()
messages.success(request, "Emailed student and resolved alert %s." % str(alert) )
l = LogEntry(userid=request.user.username,
description="Resolved alert %s." % str(alert),
related_object=form.instance)
l.save()
send_mail( form.cleaned_data['subject'], f.comments, form.cleaned_data['from_email'], [form.cleaned_data['to_email']] )
return HttpResponseRedirect(reverse('alerts.views.view_alert', kwargs={'alert_type':alert_type, 'alert_id':alert_id}))
else:
form = EmailResolutionForm(initial={'resolved_until': datetime.date.today(), 'to_email': alert.person.email(), 'from_email': request.user.email})
return render(request, 'alerts/email_alert.html', { 'alert_type':alert.alerttype,
'alert':alert,
'form': form })
示例3: _post_teardown
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def _post_teardown(self):
"""Re-enable transaction methods, and roll back any changes.
Rollback clears any DB changes made by the test so the original fixture
data is again visible.
"""
# Rollback any mutations made by tests:
for db in self._databases():
transaction.rollback(using=db)
self._urlconf_teardown()
# We do not need to close the connection here to prevent
# http://code.djangoproject.com/ticket/7572, since we commit, not
# rollback, the test fixtures and thus any cursor startup statements.
# Don't call through to superclass, because that would call
# _fixture_teardown() and close the connection.
示例4: _populate_zipcodes
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def _populate_zipcodes(self, filename):
"Open and parse a csv file, and register zipcodes"
try:
f = open(filename)
except IOError as error:
print("I/O error while opening file: <%s>" % filename,\
file=sys.stderr)
return
for line in f:
try:
line = line.split('\n')[0]
if line[0] == '#':
continue
zipcode = str(line.split(',')[0])
latitude = float(line.split(',')[3])
longitude = float(line.split(',')[4])
except IndexError as error:
print("Malformed line: <%s>" % line, file=sys.stderr)
continue
u = Zipcode(zipcode, latitude, longitude)
u.save()
print("Zipcode:%s saved" % (zipcode))
transaction.commit()
f.close()
示例5: _populate_stores
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def _populate_stores(self, filename):
"Open and parse a csv file, and register stores"
try:
f = open(filename)
except IOError as error:
print("I/O error while opening file: <%s>" % filename,\
file=sys.stderr)
return
for line in f:
try:
line = line.split('\n')[0]
if line[0] == '#':
continue
zipcode = str(line.split(',')[0])
latitude = float(line.split(',')[1])
longitude = float(line.split(',')[2])
except IndexError as error:
print("Malformed line: <%s>" % line, file=sys.stderr)
continue
s = Store(zipcode, latitude, longitude)
s.save()
print("Store:%s saved"% (zipcode))
transaction.commit()
f.close()
示例6: _populate_stores
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def _populate_stores(self, filename):
"Open and parse a csv file, and register stores"
try:
f = open(filename)
except IOError as error:
print("I/O error while opening file: <%s>" % filename,\
file=sys.stderr)
return
for line in f:
try:
line = line.split('\n')[0]
if line[0] == '#':
continue
zipcode = str(line.split(',')[1])
latitude = float(line.split(',')[2])
longitude = float(line.split(',')[3])
except IndexError as error:
print("Malformed line: <%s>" % line, file=sys.stderr)
continue
c = Competitor(zipcode, latitude, longitude)
c.save()
print("Store:%s saved"% (zipcode))
transaction.commit()
f.close()
示例7: clone_schema
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def clone_schema(self, base_schema_name, new_schema_name, set_connection=True):
"""
Creates a new schema `new_schema_name` as a clone of an existing schema
`old_schema_name`.
"""
if set_connection:
connection.set_schema_to_public()
cursor = connection.cursor()
# check if the clone_schema function already exists in the db
try:
cursor.execute("SELECT 'clone_schema'::regproc")
except ProgrammingError:
self._create_clone_schema_function()
transaction.commit()
if schema_exists(new_schema_name):
raise ValidationError("New schema name already exists")
sql = 'SELECT clone_schema(%(base_schema)s, %(new_schema)s, true, false)'
cursor.execute(
sql,
{'base_schema': base_schema_name, 'new_schema': new_schema_name}
)
cursor.close()
示例8: test_rolls_back_and_reraises_if_get_object_raises_with_uncommitted_changes
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def test_rolls_back_and_reraises_if_get_object_raises_with_uncommitted_changes(
self, mock_get_object_or_404
):
try:
# django.test.TestCase replaces the transaction management functions with nops,
# which is generally useful but breaks this test, as we're checking that the
# exception we raise isn't masked by one in the leave_transaction_management
# saying that there was a pending commit/rollback when the view returned.
restore_transaction_methods()
transaction.commit()
expected_exception = Exception("Expected exception")
def set_dirty_and_raise_exception(*args, **kwargs):
transaction.set_dirty()
raise expected_exception
mock_get_object_or_404.side_effect = set_dirty_and_raise_exception
try:
calculate_and_get_json_for_api(self.request, self.user.username, self.sheet.id)
except Exception, e:
self.assertEquals(e, expected_exception)
else:
示例9: test_commits_transaction_even_on_sheet_calculate_exception
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def test_commits_transaction_even_on_sheet_calculate_exception(
self, mock_get_object, mock_transaction
):
mock_sheet = mock_get_object.return_value
mock_sheet.calculate = self.die
mock_sheet.owner = self.user
mock_sheet.allow_json_api_access = True
self.request.method = 'POST'
self.request.POST['api_key'] = mock_sheet.api_key = 'key'
actual = calculate_and_get_json_for_api(
self.request, self.user.username, self.sheet.id)
self.assertCalledOnce(mock_transaction.commit)
self.assertTrue(isinstance(actual, HttpResponse))
self.assertEquals(actual.content, 'should not be called')
示例10: purge_trans
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def purge_trans(options):
days_opt = options['days']
days_default = False
if days_opt == -1:
days_opt = 0
days_default = True
t = Transmission.objects.filter(start_datetime__lt=timezone.now() - timedelta(days=days_opt))
print('Pruning %s transmissions older than %s days.' % (t.count(), days_opt))
t.delete()
print('Pruning complete')
if 'sqlite' in db_engine:
def vacuum_db(using='default'):
cursor = connections[using].cursor()
cursor.execute("VACUUM")
transaction.commit()
print ("Vacuuming database...")
before = os.stat(db_name).st_size
print ("Size before: %s bytes" % before)
vacuum_db()
after = os.stat(db_name).st_size
print ("Size after: %s bytes" % after)
print ("Reclaimed: %s bytes" % (before - after))
示例11: remove_reals_after_script
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def remove_reals_after_script(port_vip, ip_type, vip, port_real, priority, weight, id_ip, user):
"""
Remove real in VIP if script was completed successfully.
The script access the db when is executing.
This method is called if code returns 0.
"""
server_pool = ServerPool.objects.get(
vipporttopool__port_vip=port_vip, vipporttopool__requisicao_vip=vip)
if ip_type == IP_VERSION.IPv4[1]:
server_pool_member = ServerPoolMember.objects.get(server_pool=server_pool,
port_real=port_real,
priority=priority,
weight=weight,
ip=id_ip)
else:
server_pool_member = ServerPoolMember.objects.get(server_pool=server_pool,
port_real=port_real,
priority=priority,
weight=weight,
ipv6=id_ip)
server_pool_member.delete()
transaction.commit()
示例12: remove_pool_members
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def remove_pool_members(id_pool_member_noempty, sp, user):
# exclue server pool member
del_smp = sp.serverpoolmember_set.exclude(id__in=id_pool_member_noempty)
if del_smp:
for obj in del_smp:
obj.delete()
# execute script remove real if pool already created
# commit transaction after each successful script call
if sp.pool_created:
command = settings.POOL_REAL_REMOVE % (
obj.server_pool_id, obj.ip_id if obj.ip else obj.ipv6_id, obj.port_real)
code, _, _ = exec_script(command)
if code != 0:
raise exceptions.ScriptCreatePoolException()
transaction.commit()
示例13: process_response
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def process_response(self, request, response):
"""Commits and leaves transaction management."""
if transaction.is_managed():
if transaction.is_dirty():
# Note: it is possible that the commit fails. If the reason is
# closed connection or some similar reason, then there is
# little hope to proceed nicely. However, in some cases (
# deferred foreign key checks for exampl) it is still possible
# to rollback().
try:
transaction.commit()
except Exception:
# If the rollback fails, the transaction state will be
# messed up. It doesn't matter, the connection will be set
# to clean state after the request finishes. And, we can't
# clean the state here properly even if we wanted to, the
# connection is in transaction but we can't rollback...
transaction.rollback()
transaction.leave_transaction_management()
raise
transaction.leave_transaction_management()
return response
示例14: force_managed
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def force_managed(func):
@wraps(func)
def decorated(self, *args, **kwargs):
if not transaction.is_managed(using=self.using):
transaction.enter_transaction_management(using=self.using)
forced_managed = True
else:
forced_managed = False
try:
func(self, *args, **kwargs)
if forced_managed:
transaction.commit(using=self.using)
else:
transaction.commit_unless_managed(using=self.using)
finally:
if forced_managed:
transaction.leave_transaction_management(using=self.using)
return decorated
示例15: clone_schema
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import commit [as 别名]
def clone_schema(base_schema_name, new_schema_name, dry_run=False):
"""
Creates a new schema ``new_schema_name`` as a clone of an existing schema
``base_schema_name``.
"""
check_schema_name(new_schema_name)
cursor = connection.cursor()
# check if the clone_schema function already exists in the db
try:
cursor.execute("SELECT 'clone_schema'::regproc")
except ProgrammingError: # pragma: no cover
_create_clone_schema_function()
transaction.commit()
try:
with transaction.atomic():
sql = "SELECT clone_schema(%(base_schema)s, %(new_schema)s, TRUE)"
cursor.execute(sql, {"base_schema": base_schema_name, "new_schema": new_schema_name})
cursor.close()
if dry_run:
raise DryRunException
except DryRunException:
cursor.close()