我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.db.transaction.atomic()。
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
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
def create_tenant(name, slug, extra_data, domains=[], user=None): from shared_schema_tenants.models import Tenant with transaction.atomic(): tenant = Tenant.objects.create( name=name, slug=slug, extra_data=extra_data) if len(domains) > 0: for domain in domains: site = Site.objects.create(name=name, domain=domain) tenant.tenant_sites.create(site=site) if user: rel = tenant.relationships.create(user=user) rel.groups.add(create_default_tenant_groups()[0]) return tenant
def update_request_states_for_window_expiration(): '''Update the state of all requests and user_requests to WINDOW_EXPIRED if their last window has passed''' now = timezone.now() states_changed = False for user_request in UserRequest.objects.exclude(state__in=TERMINAL_STATES): request_states_changed = False for request in user_request.requests.filter(state='PENDING').prefetch_related('windows'): if request.max_window_time < now: logger.info('Expiring request %s', request.id, extra={'tags': {'request_num': request.id}}) with transaction.atomic(): req = Request.objects.select_for_update().get(pk=request.id) if req.state == 'PENDING': req.state = 'WINDOW_EXPIRED' states_changed = True request_states_changed = True req.save() if request_states_changed: update_user_request_state(user_request) return states_changed
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 remove_stale_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 update_heartbeat(self, hostname, heartbeat, update_freq): with transaction.atomic(): # check if there was an update in the last n seconds? interval = Now() - timedelta(seconds=update_freq) recent_worker_updates = self.filter( hostname=hostname, last_update__gte=interval, ) if recent_worker_updates.exists(): # if yes, get the latest update and move on obj = recent_worker_updates.get() else: # if no, update the worker state and move on obj, _ = self.select_for_update_or_create( hostname=hostname, defaults={'last_heartbeat': heartbeat}, ) return obj
def update_state(self, state, task_id, defaults): with transaction.atomic(): obj, created = self.select_for_update_or_create( task_id=task_id, defaults=defaults, ) if created: return obj if states.state(state) < states.state(obj.state): keep = Task.merge_rules[states.RECEIVED] else: keep = {} for key, value in defaults.items(): if key not in keep: setattr(obj, key, value) obj.save(update_fields=tuple(defaults.keys())) return obj
def handle(self, host, user, password, no_progress, *args, **options): self.s = requests.Session() self.s.auth = (user, password) self.host = host self.updated, self.inserted, self.errored, self.skipped = 0, 0, 0, 0 count = self.get('institutions/?tags=7')['count'] with transaction.atomic() and tqdm(total=count) as t: page_num = int(ceil(count / self.PER_PAGE)) for page in range(1, page_num + 1): t.set_description("Page {} of {}".format(page, page_num)) result = self.get('institutions/?tags=7&page={}'.format(page)) for row in result['results']: self.update_row(row) t.update(1) self.stdout.write( "Processed {} city halls, which {} updated, {} skipped and {} inserted. but {} errored.". format(self.updated + self.inserted, self.updated, self.skipped, self.inserted, self.errored)) total_count = CityHall.objects.count() self.stdout.write("There is {} city halls in total".format(total_count))
def handle(self, no_progress, update, *args, **options): standard, try_extended, extended = 0, 0, 0 with transaction.atomic(): for cityhall in self.get_iter(self.get_queryset(update), no_progress): guest_list = REGON.objects.filter(regonjst__jst=cityhall.original_terc).exclude(data=None).order_by('name').all() self.stdout.write(cityhall.original_name) for regon in guest_list: regon_no = self.get_regon(regon.data) self.stdout.write("** {} - {}".format(normalize(regon.name), regon_no)) if guest_list: standard += 1 if not guest_list: jst_list = JednostkaAdministracyjna.objects.area(cityhall.original_terc.parent).all() subregon_list = REGON.objects.filter(regonjst__jst__in=jst_list).exclude(data=None).order_by('name').all() try_extended += 1 if len(subregon_list) < 20: extended += 1 for regon in subregon_list: regon_no = self.get_regon(regon.data) self.stdout.write("**** {} - {}".format(normalize(regon.name), regon_no)) self.stdout.write("\n") print("Standard found {} time, extended {} times, no found {} times".format(standard, try_extended, extended))
def handle(self, comment, no_progress, dry_run, institutions_id, *args, **options): self.updated, self.skipped, self.errored = 0, 0, 0 with transaction.atomic(): for institution in self.get_iter(self.get_queryset(institutions_id), no_progress): name_resp = normalize(institution.resp.data.get('name')) name_regon = normalize(institution.regon_data.data.get('nazwa')) best_name = name_resp if len(name_resp) >= len(name_regon) else name_regon if institution.name != best_name: if dry_run: pprint({'id': institution.id, 'best_name': best_name, 'current_x': institution.name, 'resp_name': institution.resp.data.get('name'), 'regn_name': institution.regon_data.data.get('nazwa') }) institution.name = best_name if not dry_run: institution.save(update_fields=['name']) self.updated += 1 else: self.skipped += 1 self.stdout.write(("There is {} institutions changed, which " "{} updated and " "{} skipped.").format(self.updated + self.skipped, self.updated, self.skipped))
def handle(self, comment, no_progress, infile, *args, **options): self.updated, self.inserted, self.skipped, self.deactivated = 0, 0, 0, 0 self.cached_courts = {} with transaction.atomic() and reversion.create_revision(): reversion.set_comment(comment) for item in self.get_iter(self.generate_data(infile), no_progress): self.process_item(item) for obj in Court.objects.exclude(pk__in=self.cached_courts.values()).all(): obj.active = False obj.save() self.stdout.write("There is {} courts, which {} skipped, {} updated, {} inserted and {} deactivated.".format( self.updated + self.inserted + self.skipped, self.skipped, self.updated, self.inserted, self.deactivated))
def handle(self, comment, no_progress, verbose, update, *args, **options): self.updated, self.inserted, self.skipped, self.deleted, self.missing = 0, 0, 0, 0, 0 print(update) with transaction.atomic() and reversion.create_revision(): reversion.set_comment(comment) for court in self.get_iter(self.get_queryset(update), no_progress): self.process_item(court, verbose) self.stdout.write( "There is {} connection, which {} skipped, {} updated, {} deleted, {} inserted, {} missing.".format( self.updated + self.inserted + self.skipped, self.skipped, self.updated, self.deleted, self.inserted, self.missing))
def assign(self, request, pk): try: task = Task.objects.get(pk=pk, assignee=None) except Task.DoesNotExist: return Response(json.dumps({"message": "Already taken"}), status=status.HTTP_400_BAD_REQUEST) expense, created = TaskExpense.objects.get_or_create( task=task, executor_id=request.user.pk, money=task.money) if created: with transaction.atomic(): request.user.update_balance(u"???? ??????", task.money, task=task) Task.objects.filter(pk=pk, assignee=None).update(assignee=request.user) return Response(json.dumps({'message': "Taken"}), status=status.HTTP_200_OK)
def update(self, instance, validated_data): with transaction.atomic(): for attr, value in validated_data.items(): if attr == 'work_history' or attr == 'education': continue else: setattr(instance, attr, value) update_image = 'image' in validated_data instance.save(update_image=update_image) if 'work_history' in self.initial_data: update_work_history(validated_data['work_history'], instance.id) if 'education' in self.initial_data: update_education(validated_data['education'], instance.id) return instance
def process_request(self, request, data): form = ResultURLForm(self.conf, data) if form.is_valid(): with transaction.atomic(): inv_id, out_sum = form.cleaned_data['InvId'], form.cleaned_data['OutSum'] self.invoice = Invoice.objects.get(id=inv_id) # ???????? ?????? robokassa_result_received.send( sender=self.invoice.content_object.__class__, invoice=self.invoice, inv_id=inv_id, out_sum=out_sum, extra=form.extra_params() ) # ????????? ?????? self.invoice.payment_date = now() self.invoice.status_changed(options.STATUS_SUCCESS, '?????? ?????? ?? ResultURL') return HttpResponse('OK{}'.format(inv_id)) # ????? ??? ?????????, ??? ??? ???? return HttpResponse('Error: bad signature')
def process_request(self, request, data): form = SuccessRedirectForm(self.conf, data) if form.is_valid(): with transaction.atomic(): inv_id, out_sum = form.cleaned_data['InvId'], form.cleaned_data['OutSum'] self.invoice = Invoice.objects.get(id=inv_id) # ???????? ?????? robokassa_success_page_visited.send( sender=self.invoice.content_object.__class__, invoice=self.invoice, inv_id=inv_id, out_sum=out_sum, extra=form.extra_params() ) # ????????? ?????? self.invoice.status_changed(options.STATUS_SUCCESS, '????????? ?? success url') else: raise ValidationError('Robokassa data not valid') return HttpResponse('??????? ?? ?????? :)')
def process_request(self, request, data): form = FailRedirectForm(self.conf, data) if form.is_valid(): with transaction.atomic(): inv_id, out_sum = form.cleaned_data['InvId'], form.cleaned_data['OutSum'] self.invoice = Invoice.objects.get(id=inv_id) # ???????? ?????? robokassa_fail_page_visited.send( sender=self.invoice.content_object.__class__, invoice=self.invoice, inv_id=inv_id, out_sum=out_sum, extra=form.extra_params() ) # ????????? ?????? self.invoice.status_changed(options.STATUS_FAIL, '????????? ?? fail url') else: raise ValidationError('Robokassa data not valid') return HttpResponse('?????? ????????, ????? ????????????? :(')
def messages(request, room_id): if request.method == 'POST': try: room = ChatRoom.objects.get(eid=room_id) except ChatRoom.DoesNotExist: try: room = ChatRoom(eid=room_id) room.save() except IntegrityError: # someone else made the room. no problem room = ChatRoom.objects.get(eid=room_id) mfrom = request.POST['from'] text = request.POST['text'] with transaction.atomic(): msg = ChatMessage(room=room, user=mfrom, text=text) msg.save() send_event('room-%s' % room_id, 'message', msg.to_data()) body = json.dumps(msg.to_data(), cls=DjangoJSONEncoder) return HttpResponse(body, content_type='application/json') else: return HttpResponseNotAllowed(['POST'])
def save(self, *args, **kwargs): if not self.eid: counter = EventCounter.get_or_create(self.channel) with transaction.atomic(): counter = EventCounter.objects.select_for_update( ).get(id=counter.id) self.eid = counter.value + 1 try: super(Event, self).save(*args, **kwargs) except Exception: self.eid = 0 raise counter.value = self.eid counter.save() else: super(Event, self).save(*args, **kwargs)
def process_photograph_event(applicant, calendar_service, redis): """Processes the potential photograph event. It tries to submit the event to designated google calendar. And it commits to the database to prevent duplication event in the calendar. The function is atomic. """ # Uses the best effort redis redlock assumed the network is quite ok for such task. with redis.lock("{}{}".format(_PHOTOGRAPH_EVENT_LOCK_KEY_PREFIX, applicant.id)): applicant.refresh_from_db() if applicant.google_calendar_event_created_at: return with transaction.atomic(): event = populate_event_for_submitting(applicant) result = submit_photograph_event_to_calendar(calendar_service, event) commit_created_at_timestamp_in_db(applicant, result)
def handle(self, *args, **options): """ handle method for command class. """ LOGGER.info('[Transcript credentials re-encryption] Process started.') # Invalidate cached properties so that we get the latest keys invalidate_fernet_cached_properties(TranscriptCredentials, ['api_key', 'api_secret']) try: with transaction.atomic(): # Call save on each credentials record so that re-encryption can be be performed on fernet fields. for transcript_credential in TranscriptCredentials.objects.all(): transcript_credential.save() LOGGER.info('[Transcript credentials re-encryption] Process completed.') except InvalidToken: LOGGER.exception( '[Transcript credentials re-encryption] No valid fernet key present to decrypt. Process halted.' )