Python django.dispatch.receiver() Examples

The following are 30 code examples for showing how to use django.dispatch.receiver(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.dispatch , or try the search function .

Example 1
Project: Ouroboros   Author: tamuhack-org   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def create_auth_token(
    sender, instance: User = None, created: bool = False, **kwargs
) -> None:
    """
    Using Django's model signals (https://docs.djangoproject.com/en/2.2/topics/signals/), creates a new Django Rest
    Framework Token for a newly-created user, for later use with Django Rest Framework's TokenAuthentication.
    See https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication for more details.
    :param sender: The class that triggered this receiver (in this case, our User class)
    :param instance: The specific User that triggered this signal.
    :param created: Whether the user was created (or merely updated)
    :param kwargs: Other keyword arguments. See https://docs.djangoproject.com/en/2.2/topics/signals/ for more details.
    :return: None
    """
    if created:
        # This user was just created, they need a new Token!
        Token.objects.create(user=instance) 
Example 2
Project: edx-enterprise   Author: edx   File: signals.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def create_enterprise_enrollment_receiver(sender, instance, **kwargs):     # pylint: disable=unused-argument
    """
    Watches for post_save signal for creates on the CourseEnrollment table.

    Spin off an async task to generate an EnterpriseCourseEnrollment if appropriate.
    """
    if kwargs.get('created') and instance.user:
        user_id = instance.user.id
        try:
            ecu = EnterpriseCustomerUser.objects.get(user_id=user_id)
        except ObjectDoesNotExist:
            return
        logger.info((
            "User %s is an EnterpriseCustomerUser. "
            "Spinning off task to check if course is within User's "
            "Enterprise's EnterpriseCustomerCatalog."
        ), user_id)

        create_enterprise_enrollment.delay(
            str(instance.course_id),
            ecu.id,
        )


# Don't connect this receiver if we dont have access to CourseEnrollment model 
Example 3
Project: packone   Author: cas-packone   File: signals.py    License: Apache License 2.0 6 votes vote down vote up
def purge_cluster_operation(sender, instance, **kwargs):
    c_op=models.ClusterOperation.objects.filter(batch_uuid=instance.batch_uuid).first()
    if c_op and not c_op.get_sub_operations().exists():
        c_op.delete()

# @receiver(post_save, sender=models.EngineOperation)
# def operate_engine(sender,instance,created,**kwargs):
#     if created:
#         if not instance.engine.enabled:
#             raise Exception('cannot operate disabled engine')
#         if instance.operation==models.COMPONENT_OPERATION.start.value:
#             instance.engine.start(instance.pilot)
#         elif instance.operation==models.COMPONENT_OPERATION.stop.value:
#             instance.engine.stop(instance.pilot)
#         instance.completed_time=now()
#         instance.save() 
Example 4
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_decorators(self):
        data = []

        @receiver(signals.pre_save, weak=False)
        def decorated_handler(signal, sender, instance, **kwargs):
            data.append(instance)

        @receiver(signals.pre_save, sender=Car, weak=False)
        def decorated_handler_with_sender_arg(signal, sender, instance, **kwargs):
            data.append(instance)

        try:
            c1 = Car.objects.create(make="Volkswagen", model="Passat")
            self.assertEqual(data, [c1, c1])
        finally:
            signals.pre_save.disconnect(decorated_handler)
            signals.pre_save.disconnect(decorated_handler_with_sender_arg, sender=Car) 
Example 5
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_disconnect_in_dispatch(self):
        """
        Signals that disconnect when being called don't mess future
        dispatching.
        """

        class Handler:
            def __init__(self, param):
                self.param = param
                self._run = False

            def __call__(self, signal, sender, **kwargs):
                self._run = True
                signal.disconnect(receiver=self, sender=sender)

        a, b = Handler(1), Handler(2)
        signals.post_save.connect(a, sender=Person, weak=False)
        signals.post_save.connect(b, sender=Person, weak=False)
        Person.objects.create(first_name='John', last_name='Smith')

        self.assertTrue(a._run)
        self.assertTrue(b._run)
        self.assertEqual(signals.post_save.receivers, []) 
Example 6
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_decorators(self):
        data = []

        @receiver(signals.pre_save, weak=False)
        def decorated_handler(signal, sender, instance, **kwargs):
            data.append(instance)

        @receiver(signals.pre_save, sender=Car, weak=False)
        def decorated_handler_with_sender_arg(signal, sender, instance, **kwargs):
            data.append(instance)

        try:
            c1 = Car.objects.create(make="Volkswagen", model="Passat")
            self.assertEqual(data, [c1, c1])
        finally:
            signals.pre_save.disconnect(decorated_handler)
            signals.pre_save.disconnect(decorated_handler_with_sender_arg, sender=Car) 
Example 7
Project: django-notifs   Author: danidee10   File: signals.py    License: MIT License 5 votes vote down vote up
def create_notification(**kwargs):
    """Notify signal receiver."""
    warnings.warn(
        'The \'notify\' Signal will be removed in 2.6.5 '
        'Please use the helper functions in notifications.utils',
        PendingDeprecationWarning
    )

    # make fresh copy and retain kwargs
    params = kwargs.copy()
    del params['signal']
    del params['sender']

    try:
        del params['silent']
    except KeyError:
        pass

    notification = Notification(**params)

    # If it's a not a silent notification, save the notification
    if not kwargs.get('silent', False):
        notification.save()

    # Send the notification asynchronously with celery
    send_notification.delay(notification.to_json()) 
Example 8
Project: kobo-predict   Author: awemulya   File: models.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def inbox(cls, user):
        return FieldSightMessage.objects.filter(receiver=user, is_seen=False) 
Example 9
Project: kobo-predict   Author: awemulya   File: models.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def user_messages(cls, user):
        return FieldSightMessage.objects.filter(Q(sender=user) | Q(receiver=user)) 
Example 10
Project: django-cas-ng   Author: django-cas-ng   File: test_signals.py    License: MIT License 5 votes vote down vote up
def test_signal_when_user_logout_manual(monkeypatch, django_user_model):
    session = SessionStore()
    session['fake_session_key'] = 'fake-session_value'
    session.save()
    assert SessionStore(session_key=session.session_key) is not None

    factory = RequestFactory()
    request = factory.get('/logout')
    request.session = session

    # Create a fake session ticket and make sure it exists in the db
    SessionTicket.objects.create(
        session_key=session.session_key,
        ticket='fake-ticket'
    )

    user = django_user_model.objects.create_user('test@example.com', '')
    assert user is not None
    request.user = user

    callback_values = {}

    @receiver(cas_user_logout)
    def callback(sender, session, **kwargs):
        callback_values.update(kwargs)
        callback_values['session'] = dict(session)

    LogoutView().get(request)
    if django.VERSION[0] < 2:
        assert request.user.is_anonymous() is True
    else:
        assert request.user.is_anonymous is True

    assert 'user' in callback_values
    assert callback_values['user'] == user
    assert 'session' in callback_values
    assert callback_values['session'].get('fake_session_key') == 'fake-session_value'
    assert 'ticket' in callback_values
    assert callback_values['ticket'] == 'fake-ticket' 
Example 11
Project: django-cas-ng   Author: django-cas-ng   File: test_signals.py    License: MIT License 5 votes vote down vote up
def test_signal_when_user_is_created(monkeypatch, django_user_model):
    """
    Test that when CAS authentication creates a user, the signal is called with
    `created = True`
    """
    factory = RequestFactory()
    request = factory.get('/login/')
    request.session = {}

    def mock_verify(ticket, service):
        return 'test@example.com', {'ticket': ticket, 'service': service}, None

    callback_values = {}

    @receiver(cas_user_authenticated)
    def callback(sender, **kwargs):
        callback_values.update(kwargs)

    # we mock out the verify method so that we can bypass the external http
    # calls needed for real authentication since we are testing the logic
    # around authentication.
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    # sanity check
    assert not django_user_model.objects.filter(
        username='test@example.com',
    ).exists()

    backend = CASBackend()
    user = backend.authenticate(
        ticket='fake-ticket', service='fake-service', request=request,
    )

    assert 'user' in callback_values
    assert callback_values.get('user') == user
    assert callback_values.get('created') is True
    assert 'attributes' in callback_values
    assert 'ticket' in callback_values
    assert 'service' in callback_values 
Example 12
Project: django-cas-ng   Author: django-cas-ng   File: test_signals.py    License: MIT License 5 votes vote down vote up
def test_signal_when_user_already_exists(monkeypatch, django_user_model):
    """
    Test that when CAS authentication creates a user, the signal is called with
    `created = False`
    """
    factory = RequestFactory()
    request = factory.get('/login/')
    request.session = {}

    def mock_verify(ticket, service):
        return 'test@example.com', {'ticket': ticket, 'service': service}, None

    callback_values = {}

    @receiver(cas_user_authenticated)
    def callback(sender, **kwargs):
        callback_values.update(kwargs)

    # we mock out the verify method so that we can bypass the external http
    # calls needed for real authentication since we are testing the logic
    # around authentication.
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    # sanity check
    existing_user = django_user_model.objects.create_user(
        'test@example.com', '',
    )

    backend = CASBackend()
    user = backend.authenticate(
        ticket='fake-ticket', service='fake-service', request=request,
    )

    assert 'user' in callback_values
    assert callback_values.get('user') == user == existing_user
    assert callback_values.get('created') is False
    assert 'attributes' in callback_values
    assert 'ticket' in callback_values
    assert 'service' in callback_values 
Example 13
Project: django-cas-ng   Author: django-cas-ng   File: test_signals.py    License: MIT License 5 votes vote down vote up
def test_signal_not_fired_if_auth_fails(monkeypatch, django_user_model):
    """
    Test that the cas_user_authenticated signal is not fired when CAS
    authentication fails.
    """
    factory = RequestFactory()
    request = factory.get('/login/')
    request.session = {}

    def mock_verify(ticket, service):
        return None, {}, None

    callback_values = {}

    @receiver(cas_user_authenticated)
    def callback(sender, **kwargs):
        callback_values.update(kwargs)

    # we mock out the verify method so that we can bypass the external http
    # calls needed for real authentication since we are testing the logic
    # around authentication.
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    # sanity check
    backend = CASBackend()
    user = backend.authenticate(
        ticket='fake-ticket', service='fake-service', request=request,
    )

    assert user is None
    assert callback_values == {} 
Example 14
Project: hutils   Author: zaihui   File: unittest.py    License: MIT License 5 votes vote down vote up
def extend_django_sqlite():
    """ 给 django sqlite 补上一些基础函数 """

    def float_max(value_x, value_y):
        return float(max(float(value_x), float(value_y)))

    def json_contains(column_value, value):
        return json.loads(value) in json.loads(column_value)

    def json_extract(value, path):
        data = json.loads(value)
        keys = path[2:].split(".")
        result = data
        for key in keys:
            if isinstance(result, dict):
                result = result.get(key)
            else:
                result = None
        return result

    @receiver(connection_created)
    def extend_sqlite(connection=None, **_):
        if not connection or connection.vendor != "sqlite":
            return
        create_function = connection.connection.create_function
        create_function("POW", 2, pow)
        create_function("SQRT", 1, math.sqrt)
        create_function("COS", 1, math.cos)
        create_function("SIN", 1, math.sin)
        create_function("ATAN2", 2, math.atan2)
        create_function("RADIANS", 1, math.radians)
        create_function("MAX", 2, float_max)
        create_function("GREATEST", 2, max)
        create_function("FLOOR", 1, math.floor)
        create_function("JSON_CONTAINS", 2, json_contains)
        create_function("JSON_EXTRACT", 2, json_extract) 
Example 15
Project: thirtylol   Author: infinity1207   File: models.py    License: MIT License 5 votes vote down vote up
def __unicode__(self):
        return self.name

# @receiver(post_save, sender=Platform) 
Example 16
def post_transition(transition_method):
    """
    Links a post transition hook to the transition, so that our receiver can
    identify the hook.
    """

    def inner_function(func):
        @wraps(func)
        def _post_transition_hook(instance):
            return func(instance)

        setattr(transition_method, _POST_TRANSITION_IDENTIFIER, func.__name__)
        return _post_transition_hook

    return inner_function 
Example 17
Project: hoover-search   Author: liquidinvestigations   File: fixtures.py    License: MIT License 5 votes vote down vote up
def listen():
    funcs = []

    def listen(signal):
        events = []
        @receiver(signal)
        def listener(sender, **kwargs):
            events.append({k: kwargs[k] for k in kwargs
                           if k in signal.providing_args})
        funcs.append(listener)
        return events

    yield listen 
Example 18
Project: djangochannel   Author: DJWOMS   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_user_profile(sender, instance, created, **kwargs):
    """Создание профиля пользователя при регистрации"""
    if created:
        UserProfile.objects.create(user=instance, id=instance.id)
        instance.profile.save()

# @receiver(post_save, sender=User)
# def create_user_post(sender, instance, created, **kwargs):
#     """Отправка email о смене пароля пользователя"""
#     if created:
#         send_mail_edit_password(instance) 
Example 19
Project: djangochannel   Author: DJWOMS   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __str__(self):
        return "{}".format(self.record)


# @receiver(post_save, sender=Post)
# def create_user_post(sender, instance, created, **kwargs):
#     """Отправка сообщения о предложенной статье на email"""
#     if created:
#         send_mail_user_post(instance) 
Example 20
Project: django-rest-api   Author: gitgik   File: models.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        """Return a human readable representation of the model instance."""
        return "{}".format(self.name)

# This receiver handles token creation when a new user is created. 
Example 21
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def receiver(self, **kwargs):
        self.received.append(kwargs) 
Example 22
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_sender_model_name(self):
        msg = "Invalid model reference 'invalid'. String model references must be of the form 'app_label.ModelName'."
        with self.assertRaisesMessage(ValueError, msg):
            signals.post_init.connect(self.receiver, sender='invalid') 
Example 23
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_already_loaded_model(self):
        signals.post_init.connect(
            self.receiver, sender='signals.Book', weak=False
        )
        try:
            instance = Book()
            self.assertEqual(self.received, [{
                'signal': signals.post_init,
                'sender': Book,
                'instance': instance
            }])
        finally:
            signals.post_init.disconnect(self.receiver, sender=Book) 
Example 24
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_disconnect(self, apps):
        received = []

        def receiver(**kwargs):
            received.append(kwargs)

        signals.post_init.connect(receiver, sender='signals.Created', apps=apps)
        signals.post_init.disconnect(receiver, sender='signals.Created', apps=apps)

        class Created(models.Model):
            pass

        Created()
        self.assertEqual(received, []) 
Example 25
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_register_model_class_senders_immediately(self):
        """
        Model signals registered with model classes as senders don't use the
        Apps.lazy_model_operation() mechanism.
        """
        # Book isn't registered with apps2, so it will linger in
        # apps2._pending_operations if ModelSignal does the wrong thing.
        apps2 = Apps()
        signals.post_init.connect(self.receiver, sender=Book, apps=apps2)
        self.assertEqual(list(apps2._pending_operations), []) 
Example 26
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_receiver_single_signal(self):
        @receiver(a_signal)
        def f(val, **kwargs):
            self.state = val
        self.state = False
        a_signal.send(sender=self, val=True)
        self.assertTrue(self.state) 
Example 27
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_receiver_signal_list(self):
        @receiver([a_signal, b_signal, c_signal])
        def f(val, **kwargs):
            self.state.append(val)
        self.state = []
        a_signal.send(sender=self, val='a')
        c_signal.send(sender=self, val='c')
        b_signal.send(sender=self, val='b')
        self.assertIn('a', self.state)
        self.assertIn('b', self.state)
        self.assertIn('c', self.state) 
Example 28
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def receiver(self, **kwargs):
        self.received.append(kwargs) 
Example 29
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_sender_model_name(self):
        msg = "Invalid model reference 'invalid'. String model references must be of the form 'app_label.ModelName'."
        with self.assertRaisesMessage(ValueError, msg):
            signals.post_init.connect(self.receiver, sender='invalid') 
Example 30
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_already_loaded_model(self):
        signals.post_init.connect(
            self.receiver, sender='signals.Book', weak=False
        )
        try:
            instance = Book()
            self.assertEqual(self.received, [{
                'signal': signals.post_init,
                'sender': Book,
                'instance': instance
            }])
        finally:
            signals.post_init.disconnect(self.receiver, sender=Book)