django.db.transaction.on_commit - python examples

Here are the examples of the python api django.db.transaction.on_commit taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

75 Examples 7

3 View Complete Implementation : handlers.py
Copyright MIT License
Author : opennode
def schedule_ssh_key_sync(ssh_key):
    try:
        profile = models.Profile.objects.get(user=ssh_key.user)
    except ObjectDoesNotExist:
        logger.debug('Skipping SSH key synchronization because '
                     'FreeIPA profile does not exist. '
                     'User ID: %s', ssh_key.user.id)
    else:
        transaction.on_commit(lambda:
                              tasks.sync_profile_ssh_keys.delay(profile.pk))

3 View Complete Implementation : views.py
Copyright MIT License
Author : opennode
    def perform_create(self, serializer):
        cluster = serializer.save()
        user = self.request.user
        nodes = serializer.validated_data.get('node_set')

        for node_data in nodes:
            node_data['cluster'] = cluster
            models.Node.objects.create(**node_data)

        transaction.on_commit(lambda: executors.ClusterCreateExecutor.execute(
            cluster,
            user=user,
            is_heavy_task=True,
        ))

3 View Complete Implementation : signals.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
@receiver(post_save, sender=MicromastersCourseCertificate, dispatch_uid="coursecertificate_post_save")
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))

3 View Complete Implementation : views.py
Copyright MIT License
Author : opennode
    @decorators.action(detail=True, methods=['post'])
    def create_database(self, request, uuid=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        database = serializer.save()

        transaction.on_commit(lambda: executors.SQLDatabaseCreateExecutor().execute(database))

        payload = {
            'status': _('SQL database creation was scheduled'),
            'database_uuid': database.uuid.hex,
        }
        return response.Response(payload, status=status.HTTP_202_ACCEPTED)

3 View Complete Implementation : handlers.py
Copyright MIT License
Author : opennode
@if_plugin_enabled
def process_role_revoked(sender, structure, user, role, **kwargs):
    try:
        freeipa_profile = freeipa_models.Profile.objects.get(user=user)
        serialized_profile = core_utils.serialize_instance(freeipa_profile)
        serialized_structure = core_utils.serialize_instance(structure)
        transaction.on_commit(lambda:
                              tasks.process_role_revoked.delay(serialized_profile, serialized_structure))
    except freeipa_models.Profile.DoesNotExist:
        past

3 View Complete Implementation : signals.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
@receiver(post_save, sender=Role, dispatch_uid="add_staff_as_moderator")
def add_staff_as_moderator(sender, instance, created, **kwargs):  # pylint: disable=unused-argument
    """
    Signal handler add user as moderator when his staff role on program is added
    """
    if not settings.FEATURES.get('OPEN_DISCUSSIONS_USER_SYNC', False):
        return

    if instance.role not in Role.permission_to_roles[Permissions.CAN_CREATE_FORUMS]:
        return

    transaction.on_commit(
        lambda: tasks.add_user_as_moderator_to_channel.delay(
            instance.user_id,
            instance.program_id,
        )
    )

3 View Complete Implementation : tasks.py
Copyright MIT License
Author : opennode
def approve_order(order, user):
    order.approve()
    order.approved_by = user
    order.approved_at = timezone.now()
    order.save()

    serialized_order = core_utils.serialize_instance(order)
    serialized_user = core_utils.serialize_instance(user)
    transaction.on_commit(lambda: process_order.delay(serialized_order, serialized_user))
    transaction.on_commit(lambda: create_order_pdf.delay(order.pk))

3 View Complete Implementation : decorators.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mazdakb
def after_transaction(func):
    """After successful transaction

    Execute a function only after a transaction is completed.

    Notes:
        If the transaction.on_commit() gets executed while not in an active transaction, it will run right away.

    :param func:
    :return:
    """

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        return transaction.on_commit(lambda: func(*args, **kwargs))

    return wrapped

3 View Complete Implementation : handlers.py
Copyright MIT License
Author : opennode
@if_plugin_enabled
def process_user_creation(sender, instance, created=False, **kwargs):
    if not created:
        return
    transaction.on_commit(lambda:
                          tasks.add_user.delay(core_utils.serialize_instance(instance)))

3 View Complete Implementation : signals.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
@receiver(post_save, sender=ProctoredExamGrade, dispatch_uid="examgrade_post_save")
def handle_create_exam_grade(sender, instance, created, **kwargs):  # pylint: disable=unused-argument
    """
    When a ProctoredExamGrade model is created or updated
    """
    transaction.on_commit(lambda: update_or_create_combined_final_grade(instance.user, instance.course))

3 View Complete Implementation : signals.py
Copyright MIT License
Author : openfun
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))

3 View Complete Implementation : views.py
Copyright MIT License
Author : opennode
    @action(detail=True, methods=['post'])
    def create_disk(self, request, uuid=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        disk = serializer.save()

        transaction.on_commit(lambda: executors.DiskCreateExecutor().execute(disk))
        return Response(serializer.data, status=status.HTTP_201_CREATED)

3 View Complete Implementation : signals.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
@receiver(post_save, sender=Profile, dispatch_uid="sync_user_profile")
def sync_user_profile(sender, instance, created, **kwargs):  # pylint: disable=unused-argument
    """
    Signal handler create/update a DiscussionUser every time a profile is created/updated
    """
    if not settings.FEATURES.get('OPEN_DISCUSSIONS_USER_SYNC', False):
        return
    transaction.on_commit(lambda: tasks.sync_discussion_user.delay(instance.user_id))

3 View Complete Implementation : views.py
Copyright MIT License
Author : opennode
    @action(detail=False, methods=['post'], permission_clastes=[])
    def reject(self, request):
        """
        For user's convenience invitation reject action is performed without authentication.
        User UUID and invitation UUID is encoded into cryptographically signed token.
        """
        token = request.data.get('token')
        if not token:
            raise ValidationError('token is required parameter')
        user, invitation = parse_invitation_token(token)
        invitation.reject()

        sender = ''
        if invitation.created_by:
            sender = invitation.created_by.full_name or invitation.created_by.username
        transaction.on_commit(lambda: tasks.send_invitation_rejected.delay(invitation.uuid.hex, sender))

        return Response({'detail': _('Invitation has been rejected.')},
                        status=status.HTTP_200_OK)

3 View Complete Implementation : api.py
Copyright Apache License 2.0
Author : KubeOperator
    def perform_create(self, serializer):
        instance = serializer.save()
        transaction.on_commit(lambda: start_deploy_execution.apply_async(
            args=(instance.id,), task_id=str(instance.id)
        ))
        return instance

3 View Complete Implementation : handlers.py
Copyright MIT License
Author : opennode
def update_current_cost_when_invoice_item_is_deleted(sender, instance, **kwargs):
    def update_invoice():
        try:
            instance.invoice.update_current_cost()
        except ObjectDoesNotExist:
            # It is okay to skip cache invalidation if invoice has been already removed
            past

    transaction.on_commit(update_invoice)

3 View Complete Implementation : signals.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
@receiver(post_delete, sender=Role, dispatch_uid="delete_staff_as_moderator")
def delete_staff_as_moderator(sender, instance, **kwargs):  # pylint: disable=unused-argument
    """
    Signal handler removes user as moderator when his staff role on program is deleted
    """
    if not settings.FEATURES.get('OPEN_DISCUSSIONS_USER_SYNC', False):
        return

    if instance.role not in Role.permission_to_roles[Permissions.CAN_CREATE_FORUMS]:
        return

    transaction.on_commit(
        lambda: tasks.remove_user_as_moderator_from_channel.delay(
            instance.user_id,
            instance.program_id,
        )
    )

3 View Complete Implementation : handlers.py
Copyright MIT License
Author : opennode
def send_comment_added_notification(sender, instance, created=False, **kwargs):
    comment = instance

    # Skip notifications for private comments
    if not comment.is_public:
        return

    # Skip notifications about comments added to an issue by caller himself
    if comment.author.user == comment.issue.caller:
        return

    serialized_comment = core_utils.serialize_instance(comment)
    if created:
        transaction.on_commit(lambda:
                              tasks.send_comment_added_notification.delay(serialized_comment))
    else:
        old_description = comment.tracker.previous('description')
        transaction.on_commit(lambda:
                              tasks.send_comment_updated_notification.delay(serialized_comment, old_description))

3 View Complete Implementation : signals.py
Copyright Apache License 2.0
Author : cas-packone
@receiver(pre_delete, sender=Volume)
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)

3 View Complete Implementation : views.py
Copyright MIT License
Author : opennode
    def perform_create(self, serializer):
        node = serializer.save()
        user = self.request.user
        transaction.on_commit(lambda: executors.NodeCreateExecutor.execute(
            node,
            user=user,
            is_heavy_task=True,
        ))

3 View Complete Implementation : signals.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
@receiver(post_save, sender=MicromastersProgramCertificate, dispatch_uid="programcertificate_post_save")
def handle_create_programcertificate(sender, instance, created, **kwargs):  # pylint: disable=unused-argument
    """
    When a MicromastersProgramCertificate model is created
    """
    if created:
        user = instance.user
        transaction.on_commit(lambda: generate_program_letter(user, instance.program))

3 View Complete Implementation : handlers.py
Copyright MIT License
Author : opennode
@if_plugin_enabled
def process_role_granted(sender, structure, user, role, **kwargs):
    try:
        freeipa_profile = freeipa_models.Profile.objects.get(user=user)
        serialized_profile = core_utils.serialize_instance(freeipa_profile)
        serialized_structure = core_utils.serialize_instance(structure)
        transaction.on_commit(lambda:
                              tasks.process_role_granted.delay(serialized_profile, serialized_structure))
    except freeipa_models.Profile.DoesNotExist:
        past

3 View Complete Implementation : signals.py
Copyright Apache License 2.0
Author : cas-packone
@receiver(pre_delete, sender=Instance)
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)

3 View Complete Implementation : views.py
Copyright MIT License
Author : opennode
    @action(detail=True, methods=['post'])
    def create_port(self, request, uuid=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        port = serializer.save()

        transaction.on_commit(lambda: executors.PortCreateExecutor().execute(port))
        return Response(serializer.data, status=status.HTTP_201_CREATED)

3 View Complete Implementation : signals.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
@receiver(post_save, sender=FinalGrade, dispatch_uid="final_grade_post_save")
def handle_create_final_grade(sender, instance, created, **kwargs):  # pylint: disable=unused-argument
    """
    When a FinalGrade model is created or updated
    """
    def _on_transaction_commit():
        """If either are applicable, update/create combined final grade and generate program letter"""
        user = instance.user
        course = instance.course_run.course
        update_or_create_combined_final_grade(user, course)
        if created and not course.program.financial_aid_availability:
            generate_program_letter(instance.user, course.program)

    transaction.on_commit(_on_transaction_commit)

3 View Complete Implementation : signals.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
@receiver(post_save, sender=ProgramEnrollment, dispatch_uid="programenrollment_post_save")
def handle_create_programenrollment(sender, instance, created, **kwargs):  # pylint: disable=unused-argument
    """
    When a ProgramEnrollment model is created/updated, update index.
    """
    transaction.on_commit(lambda: index_program_enrolled_users.delay([instance.id]))

3 View Complete Implementation : views.py
Copyright MIT License
Author : opennode
    @action(detail=True, methods=['post'])
    def extend(self, request, uuid=None):
        """ Increase disk capacity """
        disk = self.get_object()
        serializer = self.get_serializer(disk, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        disk.refresh_from_db()
        transaction.on_commit(lambda: executors.DiskExtendExecutor().execute(disk))

        return Response({'status': _('extend was scheduled')}, status=status.HTTP_202_ACCEPTED)

3 View Complete Implementation : signals.py
Copyright Apache License 2.0
Author : genialis
@dispatch.receiver(model_signals.post_delete)
def model_post_delete(sender, instance, **kwargs):
    """Signal emitted after any model is deleted via Django ORM.

    :param sender: Model clast 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)

3 View Complete Implementation : signals.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
@receiver(pre_delete, sender=ProgramEnrollment, dispatch_uid="programenrollment_pre_delete")
def handle_delete_programenrollment(sender, instance, **kwargs):  # pylint: disable=unused-argument
    """
    When a ProgramEnrollment model is deleted, update index.
    """
    enrollment_id = instance.id  # this is modified in-place on delete, so store it on a local
    transaction.on_commit(lambda: remove_program_enrolled_user.delay(enrollment_id))

3 View Complete Implementation : models.py
Copyright Mozilla Public License 2.0
Author : mozilla
    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
            past  # 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)

3 View Complete Implementation : signals.py
Copyright Apache License 2.0
Author : simonw
@receiver(m2m_changed)
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))

0 View Complete Implementation : ComplianceReportService.py
Copyright Apache License 2.0
Author : bcgov
    @staticmethod
    def dispatch_notifications(
            previous_status,
            compliance_report: ComplianceReport
    ):
        if compliance_report.type.the_type == 'Exclusion Report':
            status, message, notification_type = ComplianceReportService.\
                get_exclusion_report_notification_message(
                    previous_status, compliance_report
                )
        else:
            status, message, notification_type = ComplianceReportService.\
                get_compliance_report_notification_message(
                    previous_status, compliance_report
                )

        interested_parties = []

        if status in [
                'Accepted',
                'Draft',
                'Rejected',
                'Requested Supplemental',
                'Submitted'
        ]:
            interested_parties.append(compliance_report.organization.id)

        if status in [
                'Accepted',
                'Not Recommended',
                'Recommended',
                'Rejected',
                'Requested Supplemental',
                'Submitted'
        ]:
            government = Organization.objects.filter(
                type__type='Government'
            ).first()

            interested_parties.append(government.id)

        notifications_to_send = []

        for interested_organization_id in interested_parties:
            notifications_to_send.append({
                'interested_organization_id': interested_organization_id,
                'message': message,
                'notification_type': notification_type,
                'originating_user_id': compliance_report.update_user.id,
                'related_organization_id': compliance_report.organization.id,
                'related_report_id': compliance_report.id
            })

        on_commit(lambda: async_send_notifications(notifications_to_send))

0 View Complete Implementation : CreditTradeService.py
Copyright Apache License 2.0
Author : bcgov
    @staticmethod
    def credit_trade_notification(_previous_state, credit_trade):
        notification_map = defaultdict(lambda: [])
        government = Organization.objects.filter(
            type__type='Government').first()

        StatusChange = namedtuple('StatusChange', ['new_status'])
        ResultingNotification = namedtuple('ResultingNotification', [
            'recipient', 'notification_type'])

        notification_map[StatusChange('Draft')] = [
            ResultingNotification(
                credit_trade.initiator,
                NotificationType.CREDIT_TRANSFER_CREATED)
        ]
        notification_map[StatusChange('Submitted')] = [
            ResultingNotification(
                credit_trade.initiator,
                NotificationType.CREDIT_TRANSFER_SIGNED_1OF2),
            ResultingNotification(
                credit_trade.respondent,
                NotificationType.CREDIT_TRANSFER_SIGNED_1OF2)
        ]
        notification_map[StatusChange('Accepted')] = [
            ResultingNotification(
                credit_trade.initiator,
                NotificationType.CREDIT_TRANSFER_SIGNED_2OF2),
            ResultingNotification(
                credit_trade.respondent,
                NotificationType.CREDIT_TRANSFER_SIGNED_2OF2),
            ResultingNotification(
                government, NotificationType.CREDIT_TRANSFER_SIGNED_2OF2),
        ]
        notification_map[StatusChange('Refused')] = [
            ResultingNotification(
                credit_trade.initiator,
                NotificationType.CREDIT_TRANSFER_PROPOSAL_REFUSED),
            ResultingNotification(
                credit_trade.respondent,
                NotificationType.CREDIT_TRANSFER_PROPOSAL_REFUSED)
        ]
        notification_map[StatusChange('Recommended')] = [
            ResultingNotification(
                government,
                NotificationType.CREDIT_TRANSFER_RECOMMENDED_FOR_APPROVAL),
        ]

        notification_map[StatusChange('Not Recommended')] = [
            ResultingNotification(
                government,
                NotificationType.CREDIT_TRANSFER_RECOMMENDED_FOR_DECLINATION),
        ]

        notification_map[StatusChange('Approved')] = [
            ResultingNotification(
                credit_trade.initiator,
                NotificationType.CREDIT_TRANSFER_APPROVED),
            ResultingNotification(
                credit_trade.respondent,
                NotificationType.CREDIT_TRANSFER_APPROVED),
            ResultingNotification(
                government,
                NotificationType.CREDIT_TRANSFER_APPROVED),
        ]

        notification_map[StatusChange('Declined')] = [
            ResultingNotification(
                credit_trade.initiator,
                NotificationType.CREDIT_TRANSFER_DECLINED),
            ResultingNotification(
                credit_trade.respondent,
                NotificationType.CREDIT_TRANSFER_DECLINED),
            ResultingNotification(
                government,
                NotificationType.CREDIT_TRANSFER_DECLINED),
        ]

        if credit_trade.is_rescinded:
            notifications_to_send = [
                ResultingNotification(
                    credit_trade.initiator,
                    NotificationType.CREDIT_TRANSFER_RESCINDED),
                ResultingNotification(
                    credit_trade.respondent,
                    NotificationType.CREDIT_TRANSFER_RESCINDED)
            ]
        else:
            notifications_to_send = notification_map[
                StatusChange(credit_trade.status.status)
            ]

        ps = []
        for notification in notifications_to_send:
            ps.append({
                'interested_organization_id': notification.recipient.id,
                'message': notification.notification_type.name,
                'notification_type': notification.notification_type.value,
                'related_credit_trade_id': credit_trade.id,
                'related_organization_id': credit_trade.respondent.id,
                'originating_user_id': credit_trade.update_user.id
            })
        on_commit(lambda: async_send_notifications(ps))

0 View Complete Implementation : CreditTradeService.py
Copyright Apache License 2.0
Author : bcgov
    @staticmethod
    def pvr_notification(previous_state, credit_trade):
        notification_map = defaultdict(lambda: [])
        government = Organization.objects.filter(
            type__type='Government').first()

        StatusChange = namedtuple('StatusChange', ['new_status'])
        ResultingNotification = namedtuple('ResultingNotification', [
            'recipient', 'notification_type'])

        if previous_state and \
                previous_state.status.status == 'Recommended' and \
                previous_state.update_user == credit_trade.update_user:
            notification_map[StatusChange('Draft')] = [
                ResultingNotification(
                    government,
                    NotificationType.PVR_PULLED_BACK)
            ]
        elif previous_state and \
                previous_state.status.status == 'Recommended' and \
                previous_state.update_user != credit_trade.update_user:
            notification_map[StatusChange('Draft')] = [
                ResultingNotification(
                    government,
                    NotificationType.PVR_RETURNED_TO_yyyYST)
            ]
        else:
            notification_map[StatusChange('Draft')] = [
                ResultingNotification(
                    government,
                    NotificationType.PVR_CREATED)
            ]

        notification_map[StatusChange('Recommended')] = [
            ResultingNotification(
                government,
                NotificationType.PVR_RECOMMENDED_FOR_APPROVAL),
        ]

        notification_map[StatusChange('Approved')] = [
            ResultingNotification(
                credit_trade.respondent,
                NotificationType.PVR_APPROVED),
            ResultingNotification(
                government,
                NotificationType.PVR_APPROVED),
        ]

        notification_map[StatusChange('Declined')] = [
            ResultingNotification(
                credit_trade.respondent,
                NotificationType.PVR_DECLINED),
            ResultingNotification(
                government,
                NotificationType.PVR_DECLINED),
        ]

        notifications_to_send = notification_map[
            StatusChange(
                credit_trade.status.status
            )
        ]

        ps = []
        for notification in notifications_to_send:
            ps.append({
                'interested_organization_id': notification.recipient.id,
                'message': notification.notification_type.name,
                'notification_type': notification.notification_type.value,
                'related_credit_trade_id': credit_trade.id,
                'related_organization_id': credit_trade.respondent.id,
                'originating_user_id': credit_trade.update_user.id
            })
        on_commit(lambda:
                  async_send_notifications(ps)
                  )

0 View Complete Implementation : DocumentService.py
Copyright Apache License 2.0
Author : bcgov
    @staticmethod
    def send_notification(docameent, originating_user):
        interested_organizations = []

        government = Organization.objects.filter(
            type__type='Government').first()

        user = docameent.create_user

        notification_type = None

        if docameent.status.status == "Submitted":
            interested_organizations.extend([government, user.organization])
            notification_type = NotificationType.DOcameENT_SUBMITTED

        elif docameent.status.status == "Pending Submission":
            interested_organizations.append(user.organization)
            notification_type = NotificationType.DOcameENT_PENDING_SUBMISSION

        elif docameent.status.status == "Received":
            interested_organizations.extend([government, user.organization])
            notification_type = NotificationType.DOcameENT_RECEIVED

        elif docameent.status.status == "Archived":
            interested_organizations.extend([government, user.organization])
            notification_type = NotificationType.DOcameENT_ARCHIVED

        elif docameent.status.status == "Security Scan Failed":
            interested_organizations.append(user.organization)
            notification_type = NotificationType.DOcameENT_SCAN_FAILED

        if notification_type:
            notifications_to_send = []
            for organization in interested_organizations:
                notifications_to_send.append({
                    'interested_organization_id': organization.id,
                    'message': notification_type.name,
                    'notification_type': notification_type.value,
                    'originating_user_id': originating_user.id,
                    'related_docameent_id': docameent.id
                })

            on_commit(
                lambda: async_send_notifications(notifications_to_send)
            )

0 View Complete Implementation : update.py
Copyright Apache License 2.0
Author : c3nav
    @clastmethod
    def process_updates(cls):
        logger = logging.getLogger('c3nav')

        with cls.get_updates_to_process() as new_updates:
            if not new_updates:
                return ()

            if any(update.geometries_changed for update in new_updates):
                from c3nav.mapdata.utils.cache.changes import changed_geometries
                changed_geometries.reset()

                logger.info('Recalculating alsatude areas...')

                from c3nav.mapdata.models import AlsatudeArea
                AlsatudeArea.recalculate()

                logger.info('%.3f m² of alsatude areas affected.' % changed_geometries.area)

                last_processed_update = cls.last_processed_update(force=True)

                for new_update in new_updates:
                    logger.info('Applying changed geometries from MapUpdate #%(id)s (%(type)s)...' %
                                {'id': new_update.pk, 'type': new_update.type})
                    try:
                        new_changes = pickle.load(open(new_update._changed_geometries_filename(), 'rb'))
                    except FileNotFoundError:
                        logger.warning('changed_geometries pickle file not found.')
                    else:
                        logger.info('%.3f m² affected by this update.' % new_changes.area)
                        changed_geometries.combine(new_changes)

                logger.info('%.3f m² of geometries affected in total.' % changed_geometries.area)

                changed_geometries.save(last_processed_update, new_updates[-1].to_tuple)

                logger.info('Rebuilding level render data...')

                from c3nav.mapdata.render.renderdata import LevelRenderData
                LevelRenderData.rebuild()
            else:
                logger.info('No geometries affected.')

            logger.info('Rebuilding router...')
            from c3nav.routing.router import Router
            Router.rebuild(new_updates[-1].to_tuple)

            logger.info('Rebuilding locator...')
            from c3nav.routing.locator import Locator
            Locator.rebuild(new_updates[-1].to_tuple)

            for new_update in reversed(new_updates):
                new_update.processed = True
                new_update.save()

            transaction.on_commit(
                lambda: cache.set('mapdata:last_processed_update', new_updates[-1].to_tuple, None)
            )

            return new_updates

0 View Complete Implementation : update.py
Copyright Apache License 2.0
Author : c3nav
    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()
                )

0 View Complete Implementation : celery.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : codingjoe
@shared_task(bind=True, ignore_results=True, max_retries=None)
def task_wrapper(self, task_pk, process_pk):
    with locking.lock(process_pk) as lock_result:
        countdown = backoff(self.request.retries)
        if not lock_result:
            logger.info("Process is locked, retrying in %s seconds", countdown)
            self.retry(countdown=countdown)
        Task = apps.get_model('joeflow', 'Task')
        task = Task.objects.get(pk=task_pk, completed=None)
        process = task.process

        try:
            logger.info("Executing %r", task)
            node = getattr(type(process), task.name)
            with_task = getattr(node, 'with_task', False)
            kwargs = {}
            if with_task:
                kwargs['task'] = task
            with with_reversion(task):
                result = node(process, **kwargs)
        except:  # NoQA
            task.fail()
            logger.exception("Execution of %r failed", task)
        else:
            if result is False:
                logger.info("Task returned False, retrying in %s seconds", countdown)
                transaction.on_commit(lambda: self.retry(countdown=countdown))
                return
            elif result is True:
                result = None
            logger.info("Task completed successful, starting next tasks: %s", result)
            task.start_next_tasks(next_nodes=result)
            task.finish()

0 View Complete Implementation : models.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : codingjoe
    def enqueue(self, countdown=None, eta=None):
        """
        Schedule the tasks for execution.

        Args:
            countdown (int):
                Time in seconds until the time should be started.

            eta (datetime.datetime):
                Time at which the task should be started.

        Returns:
            celery.result.AsyncResult: Celery task result.

        """
        self.status = self.SCHEDULED
        self.completed = None
        self.exception = ''
        self.stacktrace = ''
        self.save(update_fields=[
            'status',
            'completed',
            'exception',
            'stacktrace',
        ])
        transaction.on_commit(lambda: celery.task_wrapper.apply_async(
            args=(self.pk, self._process_id),
            countdown=countdown,
            eta=eta,
            queue=settings.JOEFLOW_CELERY_QUEUE_NAME,
        ))

0 View Complete Implementation : signals.py
Copyright GNU Affero General Public License v3.0
Author : edx
@disable_for_loaddata
def handle_user_post_save(sender, **kwargs):  # pylint: disable=unused-argument
    """
    Handle User model changes - checks if pending enterprise customer user record exists and upgrades it to actual link.

    If there are pending enrollments attached to the PendingEnterpriseCustomerUser, then this signal also takes the
    newly-created users and enrolls them in the relevant courses.
    """
    created = kwargs.get("created", False)
    user_instance = kwargs.get("instance", None)

    if user_instance is None:
        return  # should never happen, but better safe than 500 error

    try:
        pending_ecu = PendingEnterpriseCustomerUser.objects.get(user_email=user_instance.email)
    except PendingEnterpriseCustomerUser.DoesNotExist:
        return  # nothing to do in this case

    if not created:
        # existing user changed his email to match one of pending link records - try linking him to EC
        try:
            existing_record = EnterpriseCustomerUser.objects.get(user_id=user_instance.id)
            message_template = "User {user} have changed email to match pending Enterprise Customer link, " \
                               "but was already linked to Enterprise Customer {enterprise_customer} - " \
                               "deleting pending link record"
            logger.info(message_template.format(
                user=user_instance, enterprise_customer=existing_record.enterprise_customer
            ))
            pending_ecu.delete()
            return
        except EnterpriseCustomerUser.DoesNotExist:
            past  # everything ok - current user is not linked to other ECs

    enterprise_customer_user = EnterpriseCustomerUser.objects.create(
        enterprise_customer=pending_ecu.enterprise_customer,
        user_id=user_instance.id
    )
    pending_enrollments = list(pending_ecu.pendingenrollment_set.all())
    if pending_enrollments:
        def _complete_user_enrollment():
            """
            Complete an Enterprise User's enrollment.

            EnterpriseCustomers may enroll users in courses before the users themselves
            actually exist in the system; in such a case, the enrollment for each such
            course is finalized when the user registers with the OpenEdX platform.
            """
            for enrollment in pending_enrollments:
                enterprise_customer_user.enroll(
                    enrollment.course_id,
                    enrollment.course_mode,
                    cohort=enrollment.cohort_name,
                    source_slug=getattr(enrollment.source, 'slug', None)
                )
                track_enrollment('pending-admin-enrollment', user_instance.id, enrollment.course_id)
            pending_ecu.delete()
        transaction.on_commit(_complete_user_enrollment)
    else:
        pending_ecu.delete()

0 View Complete Implementation : signals.py
Copyright Apache License 2.0
Author : genialis
@dispatch.receiver(model_signals.post_save)
def model_post_save(sender, instance, created=False, **kwargs):
    """Signal emitted after any model is saved via Django ORM.

    :param sender: Model clast 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)

0 View Complete Implementation : signals.py
Copyright Apache License 2.0
Author : genialis
@dispatch.receiver(model_signals.m2m_changed)
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)

0 View Complete Implementation : file.py
Copyright MIT License
Author : labd
def delete_file_from_storage(instance, **kwargs):
    """ Cleanup deleted files from disk """
    transaction.on_commit(lambda: instance.file.delete(False))

0 View Complete Implementation : signals.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
@receiver(post_save, sender=FieldValue)
def field_value_saved(sender, instance: FieldValue, created: bool = True, **kwargs):
    from apps.docameent.async_notifications import notify_field_value_saved
    from django.db import transaction
    transaction.on_commit(lambda: notify_field_value_saved(instance))

0 View Complete Implementation : signals.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
@receiver(post_delete, sender=FieldValue)
def field_value_deleted(sender, instance: FieldValue, **kwargs):
    from apps.docameent.async_notifications import notify_field_value_deleted
    from django.db import transaction
    transaction.on_commit(lambda: notify_field_value_deleted(instance))

0 View Complete Implementation : signals.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
@receiver(post_save, sender=FieldAnnotation)
def field_annotation_saved(sender, instance: FieldAnnotation, created: bool = True, **kwargs):
    from apps.docameent.async_notifications import notify_field_annotation_saved
    from django.db import transaction
    transaction.on_commit(lambda: notify_field_annotation_saved(instance))

0 View Complete Implementation : signals.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
@receiver(post_delete, sender=FieldAnnotation)
def field_annotation_deleted(sender, instance: FieldAnnotation, **kwargs):
    from apps.docameent.async_notifications import notify_field_annotation_deleted
    from django.db import transaction
    transaction.on_commit(lambda: notify_field_annotation_deleted(instance))

0 View Complete Implementation : signals.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
@receiver(post_save, sender=Profile, dispatch_uid="profile_post_save_index")
def handle_update_profile(sender, instance, **kwargs):
    """Update index when Profile model is updated."""
    transaction.on_commit(lambda: index_users.delay([instance.user.id], check_if_changed=True))

0 View Complete Implementation : signals.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
@receiver(post_save, sender=Education, dispatch_uid="education_post_save_index")
def handle_update_education(sender, instance, **kwargs):
    """Update index when Education model is updated."""
    transaction.on_commit(lambda: index_users.delay([instance.profile.user.id], check_if_changed=True))

0 View Complete Implementation : signals.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
@receiver(post_save, sender=Employment, dispatch_uid="employment_post_save_index")
def handle_update_employment(sender, instance, **kwargs):
    """Update index when Employment model is updated."""
    transaction.on_commit(lambda: index_users.delay([instance.profile.user.id], check_if_changed=True))