Python django.dispatch.receiver() Examples
The following are 30
code examples of django.dispatch.receiver().
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.dispatch
, or try the search function
.
Example #1
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
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 #2
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
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 #3
Source File: signals.py From packone with Apache License 2.0 | 6 votes |
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
Source File: signals.py From edx-enterprise with GNU Affero General Public License v3.0 | 6 votes |
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 #5
Source File: models.py From Ouroboros with GNU General Public License v3.0 | 6 votes |
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 #6
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
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
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
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 #8
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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 #9
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def receiver(self, **kwargs): self.received.append(kwargs)
Example #10
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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 #11
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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 #12
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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 #13
Source File: models.py From djangochannel with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #14
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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 #15
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def receiver(self, **kwargs): self.received.append(kwargs)
Example #16
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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 #17
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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 #18
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_not_loaded_model(self, apps): signals.post_init.connect( self.receiver, sender='signals.Created', weak=False, apps=apps ) try: class Created(models.Model): pass instance = Created() self.assertEqual(self.received, [{ 'signal': signals.post_init, 'sender': Created, 'instance': instance }]) finally: signals.post_init.disconnect(self.receiver, sender=Created)
Example #19
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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 #20
Source File: tasks.py From esdc-ce with Apache License 2.0 | 5 votes |
def vm_replica_cb_failed_cleanup(sender, apiview, result, task_id, status, obj, **kwargs): """Signal receiver emitted after task is revoked.""" if sender == 'vm_replica': slave_vm = SlaveVm.get_by_uuid(apiview['slave_vm_uuid']) _vm_replica_cb_failed(result, task_id, obj, slave_vm, apiview['method']) # noinspection PyUnusedLocal
Example #21
Source File: tasks.py From esdc-ce with Apache License 2.0 | 5 votes |
def vm_replica_failover_cb_failed_cleanup(sender, apiview, result, task_id, status, obj, **kwargs): """Signal receiver emitted after task is revoked.""" if sender == 'vm_replica_failover': _vm_replica_failover_cb_failed(result, task_id, obj)
Example #22
Source File: signals.py From django-notifs with MIT License | 5 votes |
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 #23
Source File: models.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def inbox(cls, user): return FieldSightMessage.objects.filter(receiver=user, is_seen=False)
Example #24
Source File: models.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def user_messages(cls, user): return FieldSightMessage.objects.filter(Q(sender=user) | Q(receiver=user))
Example #25
Source File: test_signals.py From django-cas-ng with MIT License | 5 votes |
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 #26
Source File: test_signals.py From django-cas-ng with MIT License | 5 votes |
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 #27
Source File: test_signals.py From django-cas-ng with MIT License | 5 votes |
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 #28
Source File: test_signals.py From django-cas-ng with MIT License | 5 votes |
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 #29
Source File: unittest.py From hutils with MIT License | 5 votes |
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 #30
Source File: models.py From thirtylol with MIT License | 5 votes |
def __unicode__(self): return self.name # @receiver(post_save, sender=Platform)