本文整理汇总了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)
示例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
示例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()
示例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)
示例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, [])
示例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())
示例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)
示例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))
示例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'
示例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
示例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
示例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 == {}
示例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)
示例14: __unicode__
# 需要导入模块: from django import dispatch [as 别名]
# 或者: from django.dispatch import receiver [as 别名]
def __unicode__(self):
return self.name
# @receiver(post_save, sender=Platform)
示例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