def create_notification(**kwargs):
"""Notify signal receiver."""
# make fresh copy and retain kwargs
params = kwargs.copy()
del params['signal']
del params['sender']
with suppress(KeyError):
del params['silent']
silent = kwargs.get('silent', False)
# If it's a silent notification create the notification but don't save it
if silent:
notification = Notification(**params)
else:
notification = Notification.objects.create(**params)
# send via custom adapters
for adapter_path in getattr(settings, 'NOTIFICATION_ADAPTERS', []):
adapter = import_attr(adapter_path)
adapter(**kwargs).notify()
if getattr(settings, 'NOTIFICATIONS_WEBSOCKET', False):
send_to_queue(notification)
python类receiver()的实例源码
def test_post_send_exception(self):
"""All post-send receivers called, even if one throws"""
@receiver(post_send, weak=False)
def handler_1(sender, message, status, esp_name, **kwargs):
raise ValueError("oops")
self.addCleanup(post_send.disconnect, receiver=handler_1)
@receiver(post_send, weak=False)
def handler_2(sender, message, status, esp_name, **kwargs):
self.handler_2_called = True
self.addCleanup(post_send.disconnect, receiver=handler_2)
self.handler_2_called = False
with self.assertRaises(ValueError):
self.message.send()
self.assertTrue(self.handler_2_called)
def delete_spider(request):
data = {
'result': False
}
try:
guid = request.GET.get('guid', -1)
print('guid:%s' % guid)
if guid != -1 and guid != None:
red.delete(guid)
red.lrem('spiders', 1, guid)
data['result'] = True
except Exception, e:
logging.error('analysis data exception:%s' % e)
response = HttpResponse(json.dumps(data), content_type = "application/json")
return response
#
# @receiver(request_finished)
# def my_callback(sender, **kwargs):
# print("Request finished!")
#
def __str__(self):
"""Summary
Returns:
TYPE: Description
"""
return 'Tile Map Service : {}'.format(self.friendly_name)
# This receiver handles token creation when a new user is created.
def create_auth_token(sender, instance=None, created=False, **kwargs):
"""Summary
Args:
sender (TYPE): Description
instance (None, optional): Description
created (bool, optional): Description
**kwargs: Description
"""
if created:
Token.objects.create(user=instance)
# This receiver handles gee url creation when a new gee map service is created
def page_changed(sender, **kwargs):
"""
post_save receiver for Page model:
* clears Page-related cache keys,
* refresh mappings: alias <-> page real url,
* clears cache keys related to PageChanges.
"""
page = kwargs['instance']
cache_key = cachekeys.template_source(page.pk)
cache.delete(cache_key)
PageURLCache.refresh()
def update_domain_serial_when_interface_deleted(sender, instance, **kwargs):
if instance.domain is not None:
domain = instance.domain
domain.domain_serial += 1
domain.save()
if instance.ip4address is not None:
subnet = instance.ip4address.subnet
subnet.domain_serial += 1
subnet.save()
# @receiver(pre_save, sender=Domain)
# def update_domain_serial_when_domain_is_saved(sender, instance, **kwargs):
# instance.domain_serial = format_domain_serial_and_add_one(instance.domain_serial)
def validate_task(sender, instance, **kwargs):
instance.full_clean()
# @receiver(post_save, sender=Task)
def es_index_instance(sender, instance, created, **kwargs):
"""Signal receiver function for Creating/Indexing a model into
elasticsearch
"""
indexer = ModelIndex.indexer_for_instance(instance)
if indexer is not None:
indexable_func = getattr(indexer, 'indexable', None)
if callable(indexable_func):
if indexable_func():
indexer.save()
else:
indexer.delete()
else:
indexer.save()
def es_delete_instance(sender, instance, **kwargs):
"""Signal receiver function for removing indexed models from
elasticsearch
"""
indexer = ModelIndex.indexer_for_instance(instance)
if indexer is not None:
indexer.delete()
def send_pm(cls, sender, receivers, subject, content, chain=None):
chain_id = chain_id if chain else uuid.uuid4()
sent_copies = []
kept_copies = []
for receiver in receivers:
opts = {
'sender': sender,
'receiver': receiver,
'inbox': receiver,
'subject': subject,
'content': content,
'chain': chain_id
}
# Receiver's copy
pm = PrivateMessage(**opts)
pm.save()
sent_copies.append(pm)
if sender != receiver:
# Sender's copy
opts['inbox'] = sender
pm = PrivateMessage(**opts)
pm.save()
kept_copies.append(pm)
return (sent_copies, kept_copies)
def on_asset_posted(sender, instance, created, **kwargs):
print("on_asset_posted: instance={}, created={}".format(instance, created))
asset = instance
Event.process(asset, None, created)
# @receiver(notify)
# def on_notify(verb, recipient, sender, **kwargs):
# print("Notify {0} about {1} {2}".format(recipient.email, sender, verb))
# subject = None
# body = None
# template = None
# if isinstance(sender, Comment):
# comment = sender
# # asset = sender.content_object
# # if verb == 'was posted' and recipient.profile.email_comments:
# # subject =
# # template = loader.get_template('assets/notification/new_comment_posted.txt')
# # elif verb == 'mentioned' and recipient.profile.email_mention:
# # subject =
# # template = loader.get_template('assets/notification/mention.txt')
# # if template:
# # context = dict(comment=comment, asset=asset, user=recipient)
# # body = template.render(context)
#
# if isinstance(sender, Asset):
# asset = sender
# # if verb == 'was posted' and recipient.profile.email_assets:
# # subject =
# # template = loader.get_template('assets/notification/new_asset_posted.txt')
# # elif verb == 'was updated' and recipient.profile.email_assets:
# # subject =
# # template = loader.get_template('assets/notification/asset_updated.txt')
# # elif verb == 'mentioned' and recipient.profile.email_mention:
# # subject = ugettext("[{site}]: You were mentioned").format(site = comment.site.name)
# # template = loader.get_template('assets/notification/mention.txt')
# # if template:
# # context = dict(asset=asset, user=recipient)
# # body = template.render(context)
#
# if subject and body:
# send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [recipient.email], fail_silently = False)
def ready(self):
import signals
post_save.connect(receiver, sender=settings.AUTH_USER_MODEL)
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.
def test_pre_send(self):
"""Pre-send receivers invoked for each message, before sending"""
@receiver(pre_send, weak=False)
def handle_pre_send(sender, message, esp_name, **kwargs):
self.assertEqual(self.get_send_count(), 0) # not sent yet
self.assertEqual(sender, TestEmailBackend)
self.assertEqual(message, self.message)
self.assertEqual(esp_name, "Test") # the TestEmailBackend's ESP is named "Test"
self.receiver_called = True
self.addCleanup(pre_send.disconnect, receiver=handle_pre_send)
self.receiver_called = False
self.message.send()
self.assertTrue(self.receiver_called)
self.assertEqual(self.get_send_count(), 1) # sent now
def test_cancel_in_pre_send(self):
"""Pre-send receiver can cancel the send"""
@receiver(pre_send, weak=False)
def cancel_pre_send(sender, message, esp_name, **kwargs):
raise AnymailCancelSend("whoa there")
self.addCleanup(pre_send.disconnect, receiver=cancel_pre_send)
self.message.send()
self.assertEqual(self.get_send_count(), 0) # send API not called
def test_signals(self):
event_logged_counter = [0]
@receiver(signals.event_logged)
def on_event_logged(sender, **kwargs):
event_logged_counter[0] += 1
log('test', 'Testing signal')
self.assertEqual(event_logged_counter[0], 1)
def __init__(self, *args, **kwargs):
"""Create a receiver."""
super().__init__(*args, **kwargs)
self.index = Index(settings.ES_CONFIGURATION['fingerprint_index_name'])
if not self.index.exists():
self.index.create()
def test_webook_received_signal_triggered(self):
data = {'id': 123456}
# Create a test signal receiver for the generic webhook received signal.
@receiver(webhook_received)
def test_webhook_received_receiver(sender, data, **kwargs):
test_webhook_received_receiver.data = data
test_webhook_received_receiver.data = None
response = self.post_shopify_webhook(topic = 'fulfillments/update', data = data)
self.assertEqual(data, test_webhook_received_receiver.data, 'POST fulfillments/update correctly triggered webhook_received signal.')
def test_order_created_signal_triggered(self):
data = {'id': 123456}
# Create a test signal receiver for the order/created topic.
@receiver(orders_create)
def test_order_create_receiver(sender, data, **kwargs):
test_order_create_receiver.data = data
test_order_create_receiver.data = None
response = self.post_shopify_webhook(topic = 'orders/create', data = data)
self.assertEqual(data, test_order_create_receiver.data, 'POST orders/create correctly triggered order_created signal.')
def on_vote_published(sender, **kwargs):
vote = kwargs['vote']
sf = vote.submission_form
if sf and not sf.is_categorized_multicentric_and_local:
parties = sf.get_presenting_parties()
reply_receiver = None
with sudo():
try:
task = Task.objects.for_data(vote).closed().filter(task_type__group__name='EC-Office').order_by('-closed_at')[0]
reply_receiver = task.assigned_to
except IndexError:
pass
parties.send_message(_('Vote {ec_number}').format(ec_number=vote.get_ec_number()), 'submissions/vote_publish.txt',
{'vote': vote}, submission=sf.submission, reply_receiver=reply_receiver)
receivers = set()
if (sf.is_amg and not sf.is_categorized_multicentric_and_local) or sf.is_mpg:
receivers |= set(settings.ECS_AMG_MPG_VOTE_RECEIVERS)
if sf.is_categorized_multicentric_and_main:
investigators = sf.investigators.filter(ethics_commission__vote_receiver__isnull=False)
receivers |= set(investigators.values_list('ethics_commission__vote_receiver', flat=True))
bits = (
'AMG' if sf.is_amg else None,
'MPG' if sf.is_mpg else None,
sf.eudract_number if sf.is_amg else sf.submission.ec_number,
'Votum {0}'.format(vote.result),
)
name = slugify('_'.join(str(bit) for bit in bits if bit is not None))
vote_ct = ContentType.objects.get_for_model(Vote)
doc = Document.objects.get(content_type=vote_ct, object_id=vote.id)
vote_pdf = doc.retrieve_raw().read()
attachments = ((name + '.pdf', vote_pdf, 'application/pdf'),)
template = loader.get_template('meetings/email/basg.txt')
text = str(template.render({}))
for receiver in receivers:
deliver(receiver, subject=name, message=text,
from_email=settings.DEFAULT_FROM_EMAIL, attachments=attachments)
if vote.is_recessed:
meeting = sf.submission.schedule_to_meeting()
meeting.update_assigned_categories()
with sudo():
tasks = Task.objects.for_submission(sf.submission).filter(task_type__workflow_node__uid='categorization', deleted_at=None)
if tasks and not any(t for t in tasks if not t.closed_at): # XXX
tasks[0].reopen()
elif vote.is_permanent:
with sudo():
Task.objects.for_data(sf.submission).exclude(
task_type__workflow_node__uid='b2_review').open().mark_deleted()
Task.objects.filter(
content_type=ContentType.objects.get_for_model(Checklist),
data_id__in=sf.submission.checklists.values('id')
).open().mark_deleted()
elif vote.result == '2':
with sudo():
Task.objects.for_submission(sf.submission).filter(
task_type__is_dynamic=True).open().mark_deleted()
task_type = TaskType.objects.get(workflow_node__uid='b2_resubmission', workflow_node__graph__auto_start=True)
task_type.workflow_node.bind(sf.submission.workflow.workflows[0]).receive_token(None)
def paypal_notify(sender, **kwargs):
logger.debug(str('??paypal??????'))
ipn_obj = sender
logger.debug(str('STEP_0:????????????????'))
order = None
try:
order = Order.objects.get(order_number=ipn_obj.custom)
except Exception as e:
logger.debug('??????' + str(ipn_obj.custom))
return
logger.debug(str('STEP_1:?????????'))
if abs(float(ipn_obj.mc_gross)-order.order_amount) > 0.01:
logger.debug(str('?????????????[%s]?????[%s],???????[%s]' % [order.order_number,order.order_amount,ipn_obj.mc_gross]))
reason = 'amount not equal'
detail = str('???????????ID[%s]?????[%s],???????[%s]' % [order.id,order.order_amount,ipn_obj.mc_gross])
logger.debug(detail)
logger.debug(str('?????????????????????'))
abnormal_order = Abnormal_Order.create(order=order,reason=reason,detail=detail)
order.status = Order.ORDER_STATUS_ERROR
order.pay_status = 'Payment amount not equal'
order.save()
return
logger.debug(str('STEP_3:??????????????'))
paypal_account = System_Config.objects.get(name='paypal_account').val
if ipn_obj.receiver_email != paypal_account:
logger.debug(str('????????????[%s]????????[%s]??????????[%s]' % [order.order_number,ipn_obj.receiver_email,paypal_account]))
reason = 'receiver not correct'
detail = str('??????????ID[%s]????????[%s]??????????[%s]' % [ipn_obj.receiver_email,paypal_account])
logger.debug(detail)
abnormal_order = Abnormal_Order.create(order=order,reason=reason,detail=detail)
order.status = Order.ORDER_STATUS_ERROR
order.pay_status = 'Payment receiver not correct'
order.save()
return
logger.debug(str('STEP_4:????????????????'))
order.status = Order.ORDER_STATUS_PAYED_SUCCESS
order.pay_status = 'Paid Successfully'
order.money_paid = ipn_obj.mc_gross
order.save()
#?????????
from shopcart import signals
signals.order_was_payed.send(sender="Order",order=order)
return
def no_passed(self):
if self.qa_excessive_status == 4:
return True
else:
return False
# @receiver(pre_save, sender=QARecordAttribute)
# def qa_record_attribute_pre_save(sender, **kwargs):
# # move to create_qa_record
# if kwargs['instance'].qa_excessive_status == 1:
# difference = kwargs['instance'].absolute_value - kwargs['instance'].product_attribute.absolute_value
# if abs(kwargs['instance'].product_attribute.difference) < abs(difference):
# kwargs['instance'].qa_excessive_status = 2
# if kwargs['instance'].qa_record.qa_excessive_status != 2:
# kwargs['instance'].qa_record.qa_excessive_status = 2
# kwargs['instance'].qa_record.save()
# #lase, to judge each record_attribute
# if kwargs['instance'].qa_excessive_status != 1:
# qa_record_attributes = kwargs['instance'].qa_record.qa_record_attributes.all()
# status_list = [qa_record_attribute.qa_excessive_status for qa_record_attribute in qa_record_attributes if qa_record_attribute != kwargs['instance']]
# if kwargs['instance'].qa_excessive_status == 3:
# if 2 in status_list and 4 in status_list:
# kwargs['instance'].qa_record.qa_excessive_status = 6
# kwargs['instance'].qa_record.save()
# elif 2 in status_list:
# kwargs['instance'].qa_record.qa_excessive_status = 5
# kwargs['instance'].qa_record.save()
# elif 2 not in status_list and 4 in status_list:
# kwargs['instance'].qa_record.qa_excessive_status = 8
# kwargs['instance'].qa_record.save()
# elif 2 not in status_list and 3 in status_list:
# kwargs['instance'].qa_record.qa_excessive_status = 7
# kwargs['instance'].qa_record.save()
# elif 1 in status_list:
# kwargs['instance'].qa_record.qa_excessive_status = 7
# kwargs['instance'].qa_record.save()
# elif kwargs['instance'].qa_excessive_status == 4:
# if 2 in status_list:
# kwargs['instance'].qa_record.qa_excessive_status = 6
# kwargs['instance'].qa_record.save()
# elif 2 not in status_list:
# kwargs['instance'].qa_record.qa_excessive_status = 8
# kwargs['instance'].qa_record.save()