當前位置: 首頁>>代碼示例>>Python>>正文


Python dispatch.receiver方法代碼示例

本文整理匯總了Python中django.dispatch.receiver方法的典型用法代碼示例。如果您正苦於以下問題:Python dispatch.receiver方法的具體用法?Python dispatch.receiver怎麽用?Python dispatch.receiver使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.dispatch的用法示例。


在下文中一共展示了dispatch.receiver方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: create_auth_token

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
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) 
開發者ID:tamuhack-org,項目名稱:Ouroboros,代碼行數:18,代碼來源:models.py

示例2: create_enterprise_enrollment_receiver

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
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 
開發者ID:edx,項目名稱:edx-enterprise,代碼行數:27,代碼來源:signals.py

示例3: purge_cluster_operation

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
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() 
開發者ID:cas-packone,項目名稱:packone,代碼行數:18,代碼來源:signals.py

示例4: test_decorators

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
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) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:19,代碼來源:tests.py

示例5: test_disconnect_in_dispatch

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
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, []) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:25,代碼來源:tests.py

示例6: create_notification

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
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()) 
開發者ID:danidee10,項目名稱:django-notifs,代碼行數:28,代碼來源:signals.py

示例7: inbox

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
def inbox(cls, user):
        return FieldSightMessage.objects.filter(receiver=user, is_seen=False) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:4,代碼來源:models.py

示例8: user_messages

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
def user_messages(cls, user):
        return FieldSightMessage.objects.filter(Q(sender=user) | Q(receiver=user)) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:4,代碼來源:models.py

示例9: test_signal_when_user_logout_manual

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
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' 
開發者ID:django-cas-ng,項目名稱:django-cas-ng,代碼行數:41,代碼來源:test_signals.py

示例10: test_signal_when_user_is_created

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
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 
開發者ID:django-cas-ng,項目名稱:django-cas-ng,代碼行數:41,代碼來源:test_signals.py

示例11: test_signal_when_user_already_exists

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
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 
開發者ID:django-cas-ng,項目名稱:django-cas-ng,代碼行數:41,代碼來源:test_signals.py

示例12: test_signal_not_fired_if_auth_fails

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
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 == {} 
開發者ID:django-cas-ng,項目名稱:django-cas-ng,代碼行數:33,代碼來源:test_signals.py

示例13: extend_django_sqlite

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
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) 
開發者ID:zaihui,項目名稱:hutils,代碼行數:38,代碼來源:unittest.py

示例14: __unicode__

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
def __unicode__(self):
        return self.name

# @receiver(post_save, sender=Platform) 
開發者ID:infinity1207,項目名稱:thirtylol,代碼行數:6,代碼來源:models.py

示例15: post_transition

# 需要導入模塊: from django import dispatch [as 別名]
# 或者: from django.dispatch import receiver [as 別名]
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 
開發者ID:kogan,項目名稱:django-subscriptions,代碼行數:17,代碼來源:fsm_hooks.py


注:本文中的django.dispatch.receiver方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。