def uploadDonations(self,donation_list):
print("database congress size:",len(Representative.objects.all()))
for donation in donation_list:
donation_dict = {}
rep = Representative.objects.get(propublicaid=donation["propublica_candidate_id"])
sup = SuperPAC.objects.get(fecid=donation["committee_id"])
donation_dict["representative_id"] = rep.id
donation_dict["superpac_id"] = sup.id
donation_dict["amount"] = donation["amount"]
donation_dict["uid"] = donation["unique_id"]
donation_dict["support"] = donation["support_or_oppose"]
##Simple try catch block to avoid duplicate donation problems
with transaction.atomic():
##Django 1.5/1.6 transaction bug requires above check
try:
Donation.objects.create(**donation_dict)
except django.db.utils.IntegrityError:
pass
python类atomic()的实例源码
def save(self, *args, **kwargs):
with transaction.atomic():
if self.default:
TypeTax.objects.exclude(pk=self.pk).update(default=False)
else:
if not TypeTax.objects.exclude(pk=self.pk).filter(default=True).exists():
self.default = True
if self.pk:
obj = TypeTax.objects.get(pk=self.pk)
if obj.tax != self.tax:
result = super(TypeTax, self).save(*args, **kwargs)
for product in self.products.all():
for pf in product.products_final.all():
pf.recalculate()
else:
result = super(TypeTax, self).save(*args, **kwargs)
else:
result = super(TypeTax, self).save(*args, **kwargs)
return result
# atributos
def save(self, *args, **kwargs):
product_final = ProductFinal.objects.filter(pk=self.product_final_id).first()
# se comprueba que no se repite el valor de las caracteristicas especiales de los productos finales cuando sean unicas
if product_final:
if product_final.product.feature_special and product_final.product.feature_special.unique:
if ProductUnique.objects.filter(
value=self.value,
product_final__product=product_final.product
).exists():
raise ValidationError(_('Ya existe un producto final con el valor de la caracteristicas especial'))
else:
raise ValidationError(_("Product don't seleted"))
# save and update stock of product final
with transaction.atomic():
r = super(ProductUnique, self).save(*args, **kwargs)
product_final.stock_real = ProductUnique.objects.filter(product_final=product_final).aggregate(stock=Sum('stock_real'))['stock']
product_final.save()
return r
# producto estrella (solo un registro publico)
def change_password(request):
"""
Sets the new password for user.
"""
if request.is_ajax():
change_password_form = ChangePasswordForm(request.POST)
if change_password_form.is_valid():
with transaction.atomic():
if request.user.check_password(change_password_form.cleaned_data['prev_password']):
request.user.set_password(change_password_form.cleaned_data['new_password'])
request.user.save()
logger.info("User '{}' changed his password successfully.".format(request.user))
changed_password.delay(request.user.username, request.user.email)
return HttpResponse(json.dumps('?????? ??????? ???????!'), content_type='application/json')
else:
return HttpResponse(json.dumps('?????? ?????? ?? ?????????. ????????? ?? ??????? ??????.'),
content_type='application/json')
else:
return HttpResponse(status=404)
def restore_data(request):
"""
Restores the password for user.
"""
if request.method == 'POST':
forgot_form = ForgotPasswordForm(request.POST)
if forgot_form.is_valid():
with transaction.atomic():
temp_password = generate_password()
user = get_object_or_404(User, email=forgot_form.cleaned_data['email'])
user.set_password(temp_password)
user.save()
restore_account.delay(user.username, temp_password, forgot_form.cleaned_data['email'])
logger.info("The password for user: '{}' restored successfully.".format(user))
return HttpResponse(json.dumps(True), content_type='application/json')
def set_current_page(request):
"""
Changes current readed page for book of user.
"""
if request.is_ajax():
pages_form = SetCurrentPageForm(request.POST)
if pages_form.is_valid():
with transaction.atomic():
book = Book.objects.get(id=pages_form.cleaned_data['book'])
user = TheUser.objects.get(id_user=request.user)
added_book = AddedBook.objects.get(id_book=book, id_user=user)
added_book.last_page = pages_form.cleaned_data['page']
added_book.save()
logger.info("User '{}' on book with id: '{}' changed page to: '{}'."
.format(user, book.id, pages_form.cleaned_data['page']))
return HttpResponse(json.dumps(True), content_type='application/json')
else:
return HttpResponse(status=404)
def upload_avatar(request):
"""
Sets new user's avatar.
"""
with transaction.atomic():
profile_user = get_object_or_404(TheUser, auth_token=request.data.get('user_token'))
try:
profile_user.user_photo.save('user_{}.png'.format(profile_user.id), request.data.get('file'))
profile_user.save()
logger.info("User '{}' changed his avatar.".format(profile_user))
resize_image(profile_user.user_photo.path, AVATAR_WIDTH)
logger.info("Image '{}' successfully resized!".format(profile_user.user_photo.path))
return Response({'status': 200,
'detail': 'successful',
'data': {'profile_image': profile_user.user_photo.url}})
except ValidationError:
logger.info("User '{}' tried to upload not an image as avatar!".format(profile_user))
return Response({'status': 404,
'detail': 'tried to upload not an image',
'data': {}})
def sign_in(request):
"""
Creates a new user and returns status.
"""
with transaction.atomic():
if 'admin' in request.data.get('username'):
return Response({'status': 400,
'detail': 'not allowed username',
'data': {}})
user = User.objects.create_user(username=request.data.get('username'),
email=request.data.get('email'),
password=request.data.get('passw1'))
user_token = TheUser.objects.get(id_user=user).auth_token
logger.info("Created user with name: '{}' mail: '{}' and id: '{}'".format(user.username, user.email, user.id))
login(request, user)
successful_registration.delay(user.username, user.email)
return Response({'status': 200,
'detail': 'successful',
'data': {'token': user_token}})
def execute(self):
"""
Execute the PreparedBillingAgreement by creating and executing a
matching BillingAgreement.
"""
# Save the execution time first.
# If execute() fails, executed_at will be set, with no executed_agreement set.
self.executed_at = now()
self.save()
with transaction.atomic():
ret = BillingAgreement.execute(self.id)
ret.user = self.user
ret.save()
self.executed_agreement = ret
self.save()
return ret
def check_identity(self, token):
"""
Lookup token on identity service and create/update local user.
"""
logger.info("checking identity server {}".format(settings.KEL["IDENTITY_URL"]))
params = {"access_token": token}
resp = requests.get("{}/tokeninfo/".format(settings.KEL["IDENTITY_URL"]), params=params)
if not resp.ok:
return None
payload = resp.json()
with transaction.atomic():
user = next(iter(User.objects.filter(username=payload["user"]["username"])), None)
if user is None:
user = User.objects.create(username=payload["user"]["username"])
else:
user.last_login = timezone.now()
user.save()
return user
def _reconcile_policy_records(self):
"""
Reconcile policy records for this zone.
"""
with self.db_zone.lock_dirty_policy_records() as dirty_policy_records:
dirty_policies = set()
for policy_record in dirty_policy_records:
if not policy_record.deleted:
dirty_policies.add(policy_record.policy)
for policy in dirty_policies:
r53_policy = Policy(policy=policy, zone=self)
r53_policy.reconcile()
self.commit(preserve_cache=True)
for policy_record in dirty_policy_records:
try:
with transaction.atomic():
policy_record.r53_policy_record.reconcile()
self.commit(preserve_cache=True)
except ClientError as excp:
logger.exception("failed to reconcile record %r", policy_record)
self._reset_change_batch()
self._delete_orphaned_managed_records()
self.commit()
def save(self, must_create=False):
"""
Saves the current session data to the database. If 'must_create' is
True, a database error will be raised if the saving operation doesn't
create a *new* entry (as opposed to possibly updating an existing
entry).
"""
if self.session_key is None:
return self.create()
data = self._get_session(no_load=must_create)
obj = self.create_model_instance(data)
using = router.db_for_write(self.model, instance=obj)
try:
with transaction.atomic(using=using):
obj.save(force_insert=must_create, using=using)
except IntegrityError:
if must_create:
raise CreateError
raise
def _rename(self, apps, schema_editor, old_model, new_model):
ContentType = apps.get_model('contenttypes', 'ContentType')
db = schema_editor.connection.alias
if not router.allow_migrate_model(db, ContentType):
return
try:
content_type = ContentType.objects.db_manager(db).get_by_natural_key(self.app_label, old_model)
except ContentType.DoesNotExist:
pass
else:
content_type.model = new_model
try:
with transaction.atomic(using=db):
content_type.save(update_fields={'model'})
except IntegrityError:
# Gracefully fallback if a stale content type causes a
# conflict as update_contenttypes will take care of asking the
# user what should be done next.
content_type.model = old_model
else:
# Clear the cache as the `get_by_natual_key()` call will cache
# the renamed ContentType instance by its old model name.
ContentType.objects.clear_cache()
def orderline_cancel(request, order_pk, line_pk):
order = get_object_or_404(Order, pk=order_pk)
item = get_object_or_404(OrderedItem.objects.filter(
delivery_group__order=order), pk=line_pk)
form = CancelItemsForm(data=request.POST or None, item=item)
status = 200
if form.is_valid():
msg = pgettext_lazy(
'Dashboard message related to an order line',
'Cancelled item %s') % item
with transaction.atomic():
form.cancel_item()
order.create_history_entry(comment=msg, user=request.user)
messages.success(request, msg)
return redirect('dashboard:order-details', order_pk=order.pk)
elif form.errors:
status = 400
ctx = {'order': order, 'item': item, 'form': form}
return TemplateResponse(
request, 'dashboard/order/modal/cancel_line.html',
ctx, status=status)
def ship_delivery_group(request, order_pk, group_pk):
order = get_object_or_404(Order, pk=order_pk)
group = get_object_or_404(order.groups.all(), pk=group_pk)
form = ShipGroupForm(request.POST or None, instance=group)
status = 200
if form.is_valid():
with transaction.atomic():
form.save()
msg = pgettext_lazy(
'Dashboard message related to a delivery group',
'Shipped %s') % group
messages.success(request, msg)
group.order.create_history_entry(comment=msg, user=request.user)
return redirect('dashboard:order-details', order_pk=order_pk)
elif form.errors:
status = 400
ctx = {'order': order, 'group': group, 'form': form}
template = 'dashboard/order/modal/ship_delivery_group.html'
return TemplateResponse(request, template, ctx, status=status)
def cancel_order(request, order_pk):
status = 200
order = get_object_or_404(Order, pk=order_pk)
form = CancelOrderForm(request.POST or None, order=order)
if form.is_valid():
msg = pgettext_lazy('Dashboard message', 'Cancelled order')
with transaction.atomic():
form.cancel_order()
order.create_history_entry(comment=msg, user=request.user)
messages.success(request, 'Order cancelled')
return redirect('dashboard:order-details', order_pk=order.pk)
# TODO: send status confirmation email
elif form.errors:
status = 400
ctx = {'order': order}
return TemplateResponse(request, 'dashboard/order/modal/cancel_order.html',
ctx, status=status)
def remove_order_voucher(request, order_pk):
status = 200
order = get_object_or_404(Order, pk=order_pk)
form = RemoveVoucherForm(request.POST or None, order=order)
if form.is_valid():
msg = pgettext_lazy('Dashboard message', 'Removed voucher from order')
with transaction.atomic():
form.remove_voucher()
order.create_history_entry(comment=msg, user=request.user)
messages.success(request, msg)
return redirect('dashboard:order-details', order_pk=order.pk)
elif form.errors:
status = 400
ctx = {'order': order}
return TemplateResponse(request,
'dashboard/order/modal/order_remove_voucher.html',
ctx, status=status)
def run_tests(self, tested_model, count):
connection = connections[self.current_db_alias]
for (test_name, model, y_label), test_class in self.tests.items():
if model is not tested_model:
continue
benchmark_test = test_class(self, model)
with transaction.atomic(using=self.current_db_alias):
try:
benchmark_test.setup()
except SkipTest:
value = elapsed_time = None
else:
start = time()
value = benchmark_test.run()
elapsed_time = time() - start
connection.needs_rollback = True
if value is None:
value = elapsed_time
self.add_data(model, test_name, count, value, y_label=y_label)
def test_cycle(self):
# Simple cycle
a = Place.objects.create(name='a')
a.parent = a
with self.assertRaisesMessage(
InternalError, 'Cannot set itself or a descendant as parent.'):
with transaction.atomic():
with self.assertNumQueries(1):
a.save()
# Complex cycle
b = Place.objects.create(name='b', parent=a)
c = Place.objects.create(name='c', parent=b)
d = Place.objects.create(name='d', parent=c)
a.parent = d
with self.assertRaisesMessage(
InternalError, 'Cannot set itself or a descendant as parent.'):
with transaction.atomic():
with self.assertNumQueries(1):
a.save()
def language_add_new(request, language_list):
language_list = LanguageList.objects.get(name=language_list)
if request.method == 'POST':
form = AddLanguageForm(request.POST)
if "cancel" in form.data: # has to be tested before data is cleaned
return HttpResponseRedirect(reverse("view-language-list",
args=[language_list.name]))
if form.is_valid():
with transaction.atomic():
form.save()
language = Language.objects.get(
ascii_name=form.cleaned_data["ascii_name"])
try:
language_list.append(language)
except IntegrityError:
pass # automatically inserted into LanguageList.DEFAULT
return HttpResponseRedirect(reverse("language-edit",
args=[language.ascii_name]))
else: # first visit
form = AddLanguageForm()
return render_template(request, "language_add_new.html",
{"form": form})
def handle(self, request):
# Languages that may need clade updates:
updateClades = []
# Iterating form to update languages:
for entry in self.langlist:
try:
with transaction.atomic():
lang = Language.objects.get(id=entry.data['idField'])
if lang.isChanged(**entry.data):
problem = lang.setDelta(request, **entry.data)
if problem is None:
lang.save()
updateClades.append(lang)
else:
messages.error(request,
lang.deltaReport(**problem))
except Exception:
logging.exception(
'Exception in AddLanguageListTableForm.handle().',
extra=entry.data)
messages.error(request, 'Sorry, the server had problems '
'saving at least one language entry.')
return updateClades
def handle(self, request):
# Iterating form to update languages:
for entry in self.langlist:
try:
with transaction.atomic():
lang = Language.objects.get(id=entry.data['idField'])
if lang.isChanged(**entry.data):
problem = lang.setDelta(request, **entry.data)
if problem is None:
lang.save()
else:
messages.error(request,
lang.deltaReport(**problem))
except Exception:
logging.exception(
'Exception in LanguageDistributionTableForm.handle().',
extra=entry.data)
messages.error(request, 'Sorry, the server had problems '
'saving at least one language entry.')
def handle(self, request):
# Iterate entries that may be changed:
for entry in self.cogclass:
data = entry.data
cogclass = CognateClass.objects.get(
id=int(data['idField']))
# Check if entry changed and try to update:
if cogclass.isChanged(**data):
try:
with transaction.atomic():
problem = cogclass.setDelta(request, **data)
if problem is None:
cogclass.save()
else:
messages.error(
request, cogclass.deltaReport(**problem))
except Exception:
logging.exception('Problem saving CognateClass '
'in view_cognateclasses.')
messages.error(
request,
'Problem while saving entry: %s' % data)
def handle(self, request):
try:
c = CognateClass.objects.get(id=self.data['id'])
if c.isChanged(**self.data):
with transaction.atomic():
try:
problem = c.setDelta(**self.data)
if problem is None:
c.save()
else:
messages.error(request, c.deltaReport(**problem))
except Exception:
logging.exception(
'Exception handling CognateClassEditForm.')
messages.error(
request,
'Sorry, the server had problems '
'updating the cognate set.')
except CognateClass.DoesNotExist:
logging.exception('Cognate class does not exist in database.')
messages.error(
request,
"Sorry, cognate class %s does not exist on the server." %
self.data['id'])
def handle(self, request):
language = Language.objects.get(ascii_name=self.data['language'])
meanings = Meaning.objects.exclude(
id__in=set(Lexeme.objects.filter(
language=language).values_list(
'meaning_id', flat=True))).all()
if meanings:
with transaction.atomic():
for m in meanings:
Lexeme.objects.create(language=language, meaning=m)
messages.info(
request,
"Added lexemes for meanings: " +
", ".join([m.gloss for m in meanings]))
else:
messages.info(
request,
'There is at least one lexeme '
'for every meaning in the database.')
def merge_with(self, pk):
obj = self.__class__.objects.get(pk=pk)
for cj_obj in obj.cognacy:
try:
with transaction.atomic():
cj_obj.source = self
cj_obj.save()
except IntegrityError:
pass
for cc_obj in obj.cogset:
try:
cc_obj.source = self
cc_obj.save()
except IntegrityError:
pass
for lc_obj in obj.lexeme:
try:
with transaction.atomic():
lc_obj.source = self
lc_obj.save()
except IntegrityError:
pass
obj.delete()
def approve_withdraw(self, request, ahid):
ok = False
try:
with transaction.atomic():
ah = models.AccountHistory.objects.get(id=ahid)
if not ah.withdrawal.is_pending():
return JsonResponse({'ok': False, 'msg': '???????', 'code': -1})
ah.audit_withdrawal(True, request.user)
ok = True
except IntegrityError as err:
logger.error(err)
return JsonResponse({'ok': False, 'msg': '????, ???????????', 'code': -1})
if ok:
# ??????
teacher = ah.account.user.teacher
_try_send_sms(teacher.user.profile.phone, smsUtil.TPL_WITHDRAW_APPROVE, {'username':teacher.name}, 2)
return JsonResponse({'ok': True, 'msg': 'OK', 'code': 0})
def post(self, request, *args, **kwargs):
tsid = kwargs.get('tsid')
gids = request.POST.get('gids')
gid_list = gids and gids.split(',') or []
lcts = get_object_or_404(models.LiveCourseTimeSlot, pk=tsid)
try:
with transaction.atomic():
lcts.question_groups.clear()
if gid_list:
for g in models.QuestionGroup.objects.filter(
id__in=gid_list, deleted=False):
lcts.question_groups.add(g)
lcts.save()
except IntegrityError as err:
logger.error(err)
return JsonResponse(
{'ok': False, 'msg': '????, ???????????', 'code': -1})
return JsonResponse({'ok': True, 'msg': 'OK', 'code': 0})
def save_scan_list(request: Request) -> Response:
"""Save a new list."""
try:
with transaction.atomic():
scan_list = ScanList.objects.create(
name=request.data['listname'],
description=request.data['description'],
private=bool(request.data['isprivate']),
user=request.user if request.user.is_authenticated else None)
scan_list.save_tags(request.data['tags'])
# save columns
scan_list.save_columns(request.data['columns'])
return Response({
'list_id': scan_list.pk,
'token': scan_list.token
}, status=201)
except KeyError:
raise ParseError
def create(self, tenant=None, *args, **kwargs):
if not tenant:
tenant = get_current_tenant()
if tenant:
with transaction.atomic():
try:
model_instance = self.get_original_queryset().get(**kwargs)
except ObjectDoesNotExist:
model_instance = super(MultipleTenantModelManager, self).create(*args, **kwargs)
model_instance.tenants.add(tenant)
return model_instance
else:
raise TenantNotFoundError()
else:
model_instance = super(MultipleTenantModelManager, self).create(*args, **kwargs)
model_instance.tenants.add(tenant)
return model_instance