Python django.db.transaction.on_commit() Examples
The following are 30
code examples of django.db.transaction.on_commit().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.db.transaction
, or try the search function
.
Example #1
Source File: tasks.py From lego with MIT License | 7 votes |
def async_register(self, registration_id, logger_context=None): self.setup_logger(logger_context) self.registration = Registration.objects.get(id=registration_id) try: with transaction.atomic(): self.registration.event.register(self.registration) transaction.on_commit( lambda: notify_event_registration( constants.SOCKET_REGISTRATION_SUCCESS, self.registration ) ) log.info("registration_success", registration_id=self.registration.id) except EventHasClosed as e: log.warn( "registration_tried_after_started", exception=e, registration_id=self.registration.id, ) except (ValueError, IntegrityError) as e: log.error( "registration_error", exception=e, registration_id=self.registration.id ) raise self.retry(exc=e, max_retries=3)
Example #2
Source File: management.py From zentral with Apache License 2.0 | 7 votes |
def form_valid(self, form): existing_kext_policies = (KernelExtensionPolicy.objects.select_for_update() .filter(meta_business_unit=self.meta_business_unit)) # there should be at most a trashed one. try: instance = existing_kext_policies[0] except IndexError: pass else: form.instance = instance kext_policy = form.save(commit=False) kext_policy.meta_business_unit = self.meta_business_unit kext_policy.trashed_at = None kext_policy.save() form.save_m2m() transaction.on_commit(lambda: send_mbu_enrolled_devices_notifications(kext_policy.meta_business_unit)) return HttpResponseRedirect(kext_policy.get_absolute_url())
Example #3
Source File: signals.py From packone with Apache License 2.0 | 6 votes |
def materialize_volume(sender, instance, **kwargs): if not kwargs['created'] or instance.ready: return instance.built_time=now() instance.save() @transaction.atomic def materialize(volume=instance): volume=sender.objects.select_for_update().get(pk=volume.pk) remark = settings.PACKONE_LABEL+'.'+volume.cloud.name+';' if volume.remark: remark+=volume.remark info=volume.cloud.driver.volumes.create( volume.capacity, remark=remark ) volume.uuid=UUID(info.id.replace('-', ''), version=4) volume.built_time=now() volume.status=VOLUME_STATUS.available.value volume.save() materialized.send(sender=sender, instance=volume, name='materialized') transaction.on_commit(Thread(target=materialize).start)
Example #4
Source File: signals.py From packone with Apache License 2.0 | 6 votes |
def destroy_volume(sender,instance,**kwargs): #to aviold repeated deletion for volume in sender.objects.select_for_update().filter(pk=instance.pk): def destroy(): if not volume.ready: print('WARNNING: delete volume under building') else: try: volume.cloud.driver.volumes.delete( str(volume.uuid) ) except Exception as e:#TODO may spam the log volume.pk=None volume.save() traceback.print_exc() return destroyed.send(sender=sender, instance=volume, name='destroyed') transaction.on_commit(Thread(target=destroy).start)
Example #5
Source File: signals.py From packone with Apache License 2.0 | 6 votes |
def umount(sender,instance,**kwargs): #to aviold repeated deletion for mount in sender.objects.select_for_update().filter(pk=instance.pk): @transaction.atomic def destroy(mount=mount): volume=Volume.objects.select_for_update().get(pk=mount.volume.pk) if not mount.ready: print('WARNNING: delete mount under building') else: try: mount.volume.cloud.driver.volumes.unmount( str(mount.volume.uuid), str(mount.instance.uuid) ) except Exception as e: mount.pk=None mount.save() traceback.print_exc() return volume.status=VOLUME_STATUS.available.value volume.save() mount.instance.update_remedy_script(utils.remedy_script_mount_remove(mount)) destroyed.send(sender=sender, instance=mount, name='destroyed') transaction.on_commit(Thread(target=destroy).start)
Example #6
Source File: test_models.py From wagtail with BSD 3-Clause "New" or "Revised" License | 6 votes |
def tearDown(self): # delete the FieldFile directly because the TestCase does not commit # transactions to trigger transaction.on_commit() in the signal handler self.document.file.delete() self.extensionless_document.file.delete()
Example #7
Source File: signals.py From packone with Apache License 2.0 | 6 votes |
def destroy_instance(sender,instance,**kwargs): #to aviold repeated deletion for instance in sender.objects.select_for_update().filter(pk=instance.pk): def destroy(): if not instance.ready: print('WARNNING: delete instance under building') else: try: instance.cloud.driver.instances.force_delete(str(instance.uuid)) except Exception as e:#TODO may spam the log instance.pk=None instance.save() traceback.print_exc() return destroyed.send(sender=sender, instance=instance, name='destroyed') transaction.on_commit(Thread(target=destroy).start)
Example #8
Source File: signals.py From django-rest-framework-reactive with Apache License 2.0 | 6 votes |
def model_post_save(sender, instance, created=False, **kwargs): """Signal emitted after any model is saved via Django ORM. :param sender: Model class that was saved :param instance: The actual instance that was saved :param created: True if a new row was created """ if sender._meta.app_label == 'rest_framework_reactive': # Ignore own events. return def notify(): table = sender._meta.db_table if created: notify_observers(table, ORM_NOTIFY_KIND_CREATE, instance.pk) else: notify_observers(table, ORM_NOTIFY_KIND_UPDATE, instance.pk) transaction.on_commit(notify)
Example #9
Source File: signals.py From django-rest-framework-reactive with Apache License 2.0 | 6 votes |
def model_post_delete(sender, instance, **kwargs): """Signal emitted after any model is deleted via Django ORM. :param sender: Model class that was deleted :param instance: The actual instance that was removed """ if sender._meta.app_label == 'rest_framework_reactive': # Ignore own events. return def notify(): table = sender._meta.db_table notify_observers(table, ORM_NOTIFY_KIND_DELETE, instance.pk) transaction.on_commit(notify)
Example #10
Source File: signals.py From django-rest-framework-reactive with Apache License 2.0 | 6 votes |
def model_m2m_changed(sender, instance, action, **kwargs): """ Signal emitted after any M2M relation changes via Django ORM. :param sender: M2M intermediate model :param instance: The actual instance that was saved :param action: M2M action """ if sender._meta.app_label == 'rest_framework_reactive': # Ignore own events. return def notify(): table = sender._meta.db_table if action == 'post_add': notify_observers(table, ORM_NOTIFY_KIND_CREATE) elif action in ('post_remove', 'post_clear'): notify_observers(table, ORM_NOTIFY_KIND_DELETE) transaction.on_commit(notify)
Example #11
Source File: tasks.py From telemetry-analysis-service with Mozilla Public License 2.0 | 6 votes |
def provision_run(self, spark_job, first_run=False): """ Actually run the given Spark job. If this is the first run we'll update the "last_run_at" value to the start date of the spark_job so Celery beat knows what's going on. """ spark_job.run() if first_run: def update_last_run_at(): schedule_entry = spark_job.schedule.get() if schedule_entry is None: schedule_entry = spark_job.schedule.add() schedule_entry.reschedule(last_run_at=spark_job.start_date) transaction.on_commit(update_last_run_at)
Example #12
Source File: models.py From telemetry-analysis-service with Mozilla Public License 2.0 | 6 votes |
def save(self, *args, **kwargs): # whether the job is being created for the first time first_save = self.pk is None # resetting expired_date in case a user resets the end_date if self.expired_date and self.end_date and self.end_date > timezone.now(): self.expired_date = None super().save(*args, **kwargs) # Remove the cached latest run to this objects will requery it. try: delattr(self, "latest_run") except AttributeError: # pragma: no cover pass # It didn't have a `latest_run` and that's ok. # first remove if it exists self.schedule.delete() # and then add it, but only if the end date is in the future if self.has_future_end_date(timezone.now()): self.schedule.add() if first_save: transaction.on_commit(self.first_run)
Example #13
Source File: management.py From zentral with Apache License 2.0 | 6 votes |
def forms_valid(self, secret_form, enrollment_form): # make secret secret = secret_form.save() # make enrollment enrollment = enrollment_form.save(commit=False) enrollment.version = 0 enrollment.secret = secret enrollment.save() enrollment_form.save_m2m() # MDM enrollment package mep = MDMEnrollmentPackage.objects.create( meta_business_unit=secret.meta_business_unit, builder=self.builder_key, enrollment_pk=enrollment.pk ) # link from enrollment to mdm enrollment package, for config update propagation enrollment.distributor = mep enrollment.save() # build package and package manifest via callback call transaction.on_commit(lambda: send_mbu_enrolled_devices_notifications(mep.meta_business_unit)) return HttpResponseRedirect(mep.get_absolute_url())
Example #14
Source File: serializers.py From koku with GNU Affero General Public License v3.0 | 6 votes |
def create(self, validated_data): """Create a data export request.""" request = self.context.get("request") user = request.user dump_request = DataExportRequest.objects.create( created_by=user, start_date=validated_data["start_date"], end_date=validated_data["end_date"], bucket_name=validated_data["bucket_name"], ) transaction.on_commit(lambda: sync_data_to_customer.delay(dump_request.uuid)) return dump_request
Example #15
Source File: core.py From Wooey with BSD 3-Clause "New" or "Revised" License | 5 votes |
def submit_to_celery(self, **kwargs): if kwargs.get('resubmit'): params = self.get_parameters() user = kwargs.get('user') self.pk = None self.user = None if user is None or not user.is_authenticated else user # clear the output channels self.celery_id = None self.uuid = uuid.uuid4() self.stdout = '' self.stderr = '' self.save() with transaction.atomic(): for param in params: param.pk = None param.job = self param.recreate() param.save() self.status = self.SUBMITTED self.save() task_kwargs = {'wooey_job': self.pk, 'rerun': kwargs.pop('rerun', False)} if task_kwargs.get('rerun'): utils.purge_output(job=self) if wooey_settings.WOOEY_CELERY: transaction.on_commit(lambda: tasks.submit_script.delay(**task_kwargs)) else: transaction.on_commit(lambda: tasks.submit_script(**task_kwargs)) return self
Example #16
Source File: tests.py From django-sqlserver with MIT License | 5 votes |
def do(self, num): """Create a Thing instance and notify about it.""" Thing.objects.create(num=num) transaction.on_commit(lambda: self.notify(num))
Example #17
Source File: signals.py From simonwillisonblog with Apache License 2.0 | 5 votes |
def make_updater(instance): components = instance.index_components() pk = instance.pk def on_commit(): search_vectors = [] for weight, text in list(components.items()): search_vectors.append( SearchVector(Value(text, output_field=TextField()), weight=weight) ) instance.__class__.objects.filter(pk=pk).update( search_document=reduce(operator.add, search_vectors) ) return on_commit
Example #18
Source File: signals.py From micromasters with BSD 3-Clause "New" or "Revised" License | 5 votes |
def handle_update_percolate(sender, instance, **kwargs): """When a new query is created or a query is updated, update Elasticsearch too""" transaction.on_commit(lambda: index_percolate_queries.delay([instance.id]))
Example #19
Source File: signals.py From micromasters with BSD 3-Clause "New" or "Revised" License | 5 votes |
def handle_create_role(sender, instance, **kwargs): """Update index when Role model instance is created.""" transaction.on_commit(lambda: index_users.delay([instance.user.id]))
Example #20
Source File: signals.py From micromasters with BSD 3-Clause "New" or "Revised" License | 5 votes |
def handle_delete_percolate(sender, instance, **kwargs): """When a query is deleted, make sure we also delete it on Elasticsearch""" transaction.on_commit(lambda: delete_percolate_query.delay(instance.id))
Example #21
Source File: signals.py From micromasters with BSD 3-Clause "New" or "Revised" License | 5 votes |
def handle_create_coursecertificate(sender, instance, created, **kwargs): # pylint: disable=unused-argument """ When a MicromastersCourseCertificate model is created """ if created: user = instance.user program = instance.course.program transaction.on_commit(lambda: generate_program_certificate(user, program))
Example #22
Source File: signals.py From simonwillisonblog with Apache License 2.0 | 5 votes |
def on_save(sender, **kwargs): if not issubclass(sender, BaseModel): return transaction.on_commit(make_updater(kwargs["instance"]))
Example #23
Source File: signals.py From simonwillisonblog with Apache License 2.0 | 5 votes |
def on_m2m_changed(sender, **kwargs): instance = kwargs["instance"] model = kwargs["model"] if model is Tag: transaction.on_commit(make_updater(instance)) elif isinstance(instance, Tag): for obj in model.objects.filter(pk__in=kwargs["pk_set"]): transaction.on_commit(make_updater(obj))
Example #24
Source File: signals.py From richie with MIT License | 5 votes |
def on_page_publish(sender, instance, language, **kwargs): """ Trigger update of the Elasticsearch indices impacted by the modification of the instance only once the database transaction is successful. """ if getattr(settings, "RICHIE_KEEP_SEARCH_UPDATED", True): transaction.on_commit(lambda: update_page_extension(instance, language))
Example #25
Source File: locations.py From c3nav with Apache License 2.0 | 5 votes |
def delete(self, *args, **kwargs): with transaction.atomic(): super().delete(*args, **kwargs) transaction.on_commit(lambda: cache.delete('user_has_positions:%d' % self.owner_id))
Example #26
Source File: access.py From c3nav with Apache License 2.0 | 5 votes |
def delete(self, *args, **kwargs): with transaction.atomic(): super().delete(*args, **kwargs) transaction.on_commit(lambda: cache.delete(self.user_access_permission_key(self.user_id)))
Example #27
Source File: access.py From c3nav with Apache License 2.0 | 5 votes |
def save(self, *args, **kwargs): with transaction.atomic(): super().save(*args, **kwargs) transaction.on_commit(lambda: cache.delete(self.user_access_permission_key(self.user_id)))
Example #28
Source File: update.py From c3nav with Apache License 2.0 | 5 votes |
def save(self, **kwargs): new = self.pk is None if not new and (self.was_processed or not self.processed): raise TypeError from c3nav.mapdata.utils.cache.changes import changed_geometries if self.geometries_changed is None: self.geometries_changed = not changed_geometries.is_empty super().save(**kwargs) with suppress(FileExistsError): os.mkdir(os.path.dirname(self._changed_geometries_filename())) if self.geometries_changed: pickle.dump(changed_geometries, open(self._changed_geometries_filename(), 'wb')) if new: transaction.on_commit( lambda: cache.set('mapdata:last_update', self.to_tuple, None) ) if settings.HAS_CELERY and settings.AUTO_PROCESS_UPDATES: transaction.on_commit( lambda: process_map_updates.delay() )
Example #29
Source File: models.py From c3nav with Apache License 2.0 | 5 votes |
def save(self, **kwargs): new = self.pk is None with transaction.atomic(): super().save(**kwargs) if new: transaction.on_commit( lambda: cache.set('site:last_site_update', self.pk, None) )
Example #30
Source File: management.py From zentral with Apache License 2.0 | 5 votes |
def form_valid(self, form): self.configuration_profile = form.save() transaction.on_commit(lambda: send_mbu_enrolled_devices_notifications(self.meta_business_unit)) return super().form_valid(form)