def test_new_receiver_gets_only_overriden_signal(self): u""" Checks that receivers registered inside ``override_signals`` context get only signals emitted inside the context block. """ signal = Signal(providing_args=[u'message']) signal.send(sender=None, message=u'before') with override_signals(signal): new_receiver = mock.Mock() signal.connect(new_receiver) signal.send(sender=None, message=u'overriden') signal.send(sender=None, message=u'after') self.assertEqual(new_receiver.mock_calls, [ mock.call(message=u'overriden', sender=None, signal=signal), ])
def test_original_receiver_does_not_get_overriden_signal(self): u""" Checks that receivers registered outside ``override_signals`` context do not get signals emitted inside the context block. """ signal = Signal(providing_args=[u'message']) original_receiver = mock.Mock() signal.connect(original_receiver) signal.send(sender=None, message=u'before') with override_signals(signal): signal.send(sender=None, message=u'overriden') signal.send(sender=None, message=u'after') self.assertEqual(original_receiver.mock_calls, [ mock.call(message=u'before', sender=None, signal=signal), mock.call(message=u'after', sender=None, signal=signal), ])
def mockSignal(self, signal: Signal) -> typing.Iterator[mock.Mock]: # pylint: disable=invalid-name """Context manager to attach a mock to the given signal.""" # This function is only here to create an autospec. From the documentation: # # Notice that the function takes a sender argument, along with wildcard keyword arguments # (**kwargs); all signal handlers must take these arguments. # # https://docs.djangoproject.com/en/dev/topics/signals/#connecting-to-specific-signals def callback(sender: models.Model, **kwargs: typing.Any) -> None: # pragma: no cover # pylint: disable=unused-argument pass signal_mock = mock.create_autospec(callback, spec_set=True) signal.connect(signal_mock) try: yield signal_mock finally: signal.disconnect(signal_mock)
def test_dispatcher_sends_via_http(self): test_signal = Signal() async_connect(http_test_handler, spooler='test_http', signal=test_signal, sender=Person) data = {} def testview(request, spooler): data.update({ 'spooler': spooler, 'data': request.POST.copy(), }) from django.http import HttpResponse return HttpResponse('OK') person = Person() with URLOverride((r'^spooler/(?P<spooler>.+)/$', testview)): test_signal.send(instance=person, sender=Person) print data assert data['spooler'] == 'test_http' assert data['data']['instance'] == str(person.id)
def test_email_not_sent_when_watcher_removed(self, notifications): dispatch_uid = "publicweb.models.decision_signal_handler" Signal.disconnect(signals.post_save, sender=Decision, dispatch_uid=dispatch_uid) decision = self.create_and_return_decision() data = { 'description': decision.description, 'status': decision.status, 'deadline': decision.deadline, 'people': decision.people, 'watch': True } form = DecisionForm(data, instance=decision) form.watch = False form.is_valid() form.save() Signal.connect( signals.post_save, sender=Decision, receiver=decision_signal_handler, dispatch_uid=dispatch_uid ) self.assertFalse(notifications.called)
def test_submit(self): # XXX Move this to MPSigAsyncTest self.manager = TestSpoolManager() sc = SigAsyncContainer(manager=self.manager) self._container = Process(target=sc.run, args=()) self._container.start() try: async_test1 = Signal() async_connect(pass_handler, signal=async_test1, sender=Person) p = Person() async_test1.send(sender=Person, instance=p) try: self.manager._processed.get(timeout=1) except Empty: try: (s, f) = self.manager._failed.get_nowait() except Empty: raise AssertionError("Timed out waiting for entry to process") else: raise AssertionError("Job failed") finally: os.kill(self._container.pid, signal.SIGINT) self._container.join()
def test_with_multiple_signals(self): signal1 = Signal(providing_args=[u'message']) signal2 = Signal(providing_args=[u'message']) original_receiver = mock.Mock() signal1.connect(original_receiver) signal2.connect(original_receiver) signal1.send(sender=None, message=u'before') signal2.send(sender=None, message=u'before') with override_signals(signal1, signal2): new_receiver = mock.Mock() signal1.connect(new_receiver) signal2.connect(new_receiver) signal1.send(sender=None, message=u'overriden') signal2.send(sender=None, message=u'overriden') signal1.send(sender=None, message=u'after') signal2.send(sender=None, message=u'after') self.assertEqual(original_receiver.mock_calls, [ mock.call(message=u'before', sender=None, signal=signal1), mock.call(message=u'before', sender=None, signal=signal2), mock.call(message=u'after', sender=None, signal=signal1), mock.call(message=u'after', sender=None, signal=signal2), ]) self.assertEqual(new_receiver.mock_calls, [ mock.call(message=u'overriden', sender=None, signal=signal1), mock.call(message=u'overriden', sender=None, signal=signal2), ])
from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django.dispatch.dispatcher import Signal from django_fsm.signals import post_transition from bluebottle.donations.models import Donation from bluebottle.payments.models import OrderPayment from bluebottle.payments.services import PaymentService from bluebottle.utils.utils import StatusDefinition order_requested = Signal(providing_args=["order"]) @receiver(post_save, weak=False, sender=Donation, dispatch_uid='donation_model') def update_order_amount_post_save(sender, instance, **kwargs): instance.order.update_total() @receiver(post_delete, weak=False, sender=Donation, dispatch_uid='donation_model') def update_order_amount(sender, instance, **kwargs): # If we're deleting order and donations do nothing. # If we're just deleting a donation then we should update the order total. # Import it here to avoid circular imports
domain_name = application.domain config = CareplanConfig.for_domain(domain_name) if application.doc_type == 'Application-Deleted': if application.has_careplan_module: careplan_removed(domain_name, config, application.get_id) def update_project_careplan_config_release(sender, application, **kwargs): domain_name = application.domain config = CareplanConfig.for_domain(domain_name) parent_app_id = application.copy_of latest_app = application.get_latest_app(released_only=True) if latest_app and latest_app.is_released and latest_app.has_careplan_module: config = config or CareplanConfig(domain=domain_name) update_careplan_config(config, parent_app_id, latest_app) else: careplan_removed(domain_name, config, parent_app_id) successful_form_received.connect(get_custom_response_message) app_post_save = Signal(providing_args=['application']) app_post_save.connect(create_app_structure_repeat_records) app_post_save.connect(update_project_careplan_config) app_post_release = Signal(providing_args=['application']) app_post_release.connect(update_project_careplan_config_release)
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import jwt from django.conf import settings as django_settings from django.core.cache import cache from django.dispatch.dispatcher import Signal from django.utils.decorators import classproperty from django.utils.module_loading import import_string from six import text_type import requests user_jwt_logged_in = Signal(['request', 'user']) DEFAULT_JWT_AUTH_SETTING = { 'PREFIX': 'JWT', 'ALGORITHM': 'HS256', 'DECODER': 'django_jwt_session_auth.jwt_decoder', 'ENCODER': 'django_jwt_session_auth.jwt_encoder', 'SECRET': '', # default is django.conf.settings.SECRET_KEY 'PAYLOAD_TO_USER': None, 'USER_TO_PAYLOAD': None, 'USER_KEY': 'pk', 'TEST_USER_GETTER': None, 'SESSION': { 'EXPIRE': 3600 * 24 * 2, 'PREFIX': 'JWT_AUTH_CACHE:' }
from actstream.signals import action from django.contrib.admin.options import get_content_type_for_model from django.db.models.signals import post_save from django.dispatch.dispatcher import receiver, Signal from tunga.settings import WHITE_PAPER_SHEET_ID from tunga_activity import verbs from tunga_messages.models import Channel from tunga_tasks.models import Task from tunga_utils.models import ContactRequest, Upload, InviteRequest from tunga_utils.notifications.generic import notify_new_contact_request, notify_new_invite_request from tunga_profiles.models import WhitePaperUser from tunga_utils.helpers import save_to_google_sheet post_nested_save = Signal(providing_args=["instance", "created"]) post_field_update = Signal(providing_args=["instance", "field"]) @receiver(post_save, sender=ContactRequest) def activity_handler_new_contact_request(sender, instance, created, **kwargs): if created: notify_new_contact_request.delay(instance.id) @receiver(post_save, sender=Upload) def activity_handler_new_upload(sender, instance, created, **kwargs): if created and instance.content_type in [ get_content_type_for_model(Channel), get_content_type_for_model(Task) ]: action.send(instance.user,
from django import template, http from django.conf import settings from django.dispatch.dispatcher import Signal from django.template import loader from django.template.loader import render_to_string, BaseLoader from django.test.testcases import TestCase build_response = Signal() def buildresponse(sender, **kwargs): for name in dir(http): obj = getattr(http, name) if getattr(obj, 'status_code', None) == sender.status_code: sender.response = obj(sender.content) return build_response.connect(buildresponse) view = Signal() class expertmiddleware: def __init__(self): loader.template_source_loaders = (templateloader(),) def process_request(self, request): view.send(sender=request) if hasattr(request, 'response'): return request.response render_template = Signal()
from django.dispatch.dispatcher import Signal django_social_user_pre_auth = Signal(providing_args=['request']) django_social_user_post_callback = Signal(providing_args=['request']) django_social_user_pre_callback = Signal(providing_args=['request'])
import json from django.db.models.signals import post_save from django.dispatch.dispatcher import Signal from django_facebook import signals from django_facebook.utils import get_user_model from bidding.models import Auction from bidding.models import ConfigKey from bidding.models import Invitation import client import message.value_objects as vo import message.value_objects_factory as vo_factory logger = logging.getLogger('django') precap_finished_signal = Signal(providing_args=["auction"]) def auctionCreated(**kwargs): if 'created' in kwargs and kwargs['created']: auction = kwargs.get('instance') client.auction_created(auction) post_save.connect(auctionCreated, Auction) def fb_user_registered_handler(sender, user, facebook_data, **kwargs): logger.debug('fb_user_registered_handler') member = user member.bids_left = 0
from django.dispatch.dispatcher import Signal message_received = Signal(providing_args=['message']) email_sent = Signal(providing_args=['outgoing_email']) email_failed_to_send = Signal(providing_args=['outgoing_email'])
from django.dispatch.dispatcher import Signal from order.models import Checkout from inventory.models import Product def update_product_quantity_handler(checkout:Checkout): product = checkout.product product.qty = product.qty - checkout.amount product.save() Signal.connect(receiver=update_product_quantity_handler, sender=Checkout, dispatch_uid="update_product_quantity_handler")
from django.dispatch.dispatcher import Signal defcon_one_reached = Signal()
if app and hasattr(app, "langs"): try: lang = xform.openrosa_headers[OPENROSA_ACCEPT_LANGUAGE] except (AttributeError, KeyError): lang = "default" if lang == "default": lang = app.build_langs[0] if app.build_langs else None message = app.success_message.get(lang) if message: success_message = SuccessMessage(message, userID, domain=domain, tz=timedelta(hours=0)).render() return ReceiverResult( xml.get_simple_response_xml(success_message, nature=ResponseNature.SUBMIT_SUCCESS), Certainty.STRONG ) def create_app_structure_repeat_records(sender, application, **kwargs): from corehq.apps.app_manager.models import AppStructureRepeater domain = application.domain if domain: repeaters = AppStructureRepeater.by_domain(domain) for repeater in repeaters: repeater.register(application) successful_form_received.connect(get_custom_response_message) app_post_save = Signal(providing_args=["application"]) app_post_save.connect(create_app_structure_repeat_records)
# # A copy of this license - GNU General Public License - is available # at the root of the source code of this program. If not, # see http://www.gnu.org/licenses/. # ############################################################################## from django.conf import settings from django.contrib.auth.models import Group from django.db.models.signals import post_save, post_delete from django.dispatch.dispatcher import receiver, Signal from django.core.exceptions import ObjectDoesNotExist from base import models as mdl from osis_common.models.serializable_model import SerializableModel from osis_common.models.signals.authentication import user_created_signal, user_updated_signal person_created = Signal(providing_args=['person']) GROUP_STUDENTS = "students" GROUP_STUDENTS_INTERNSHIP = "internship_students" GROUP_TUTORS = "tutors" @receiver(user_created_signal) @receiver(user_updated_signal) def update_person(sender, **kwargs): user = kwargs.get('user') user_infos = kwargs.get('user_infos') person = mdl.person.find_by_global_id(user_infos.get('USER_FGS')) person = _create_update_person(user, person, user_infos) _add_person_to_group(person) return person
# -*- coding: utf-8 -*- from django.dispatch.dispatcher import Signal from account.models import DeviceUser post_save_order = Signal(providing_args=['order']) def post_save_order_receiver(sender, order, **kwargs): from .models import BALANCE_KIND_CREDIT, ORDER_AUTHORIZED, OPENED, DELIVERING, DELIVERED, CANCELED from .models import BalanceOperation import decimal print 'POST SAVE ORDER - %.2f' % order.total if order.status == ORDER_AUTHORIZED and order.payment_type.gain_credit and not order.operations.all( ): value_company = order.total tax = 0 if order.company.commission_value: value_company = order.total - order.total * order.company.commission_value / decimal.Decimal( 100) tax = order.company.commission_value BalanceOperation.objects.create(company=order.company, kind=BALANCE_KIND_CREDIT, value=order.total, value_company=value_company, tax=tax, order=order) message = None
from django.db.models.signals import post_save from django.db.utils import DatabaseError import logging from .update import PassbookChannels from django.conf import settings from django.dispatch.dispatcher import Signal logger = logging.getLogger("passbook") NOTIFICATION_CLASS = getattr(settings, "NOTIFICATION_CLASS", "PassbookChannels") if NOTIFICATION_CLASS == "PassbookChannels": channel_instance = PassbookChannels() channel = channel_instance.notify logger.debug("Use Apple APN for pass") else: channel = NOTIFICATION_CLASS() logger.debug("Use Custom channel") pass_update = Signal(providing_args=["signer", "token"]) def notify_device(sender, signer, token, **kwarg): logger.debug("receive notification") channel(signer, token) pass_update.connect(notify_device)
from django.dispatch.dispatcher import Signal # Publication events content_published = Signal(providing_args=["instance", "user", "by_email"]) content_unpublished = Signal( providing_args=["instance", "target", "moderator"]) content_read = Signal(providing_args=["instance", "user", "target"])
# vim: expandtab # -*- coding: utf-8 -*- from django.dispatch.dispatcher import Signal message_sent = Signal(providing_args=['message']) message_received = Signal(providing_args=['message'])
from django.dispatch.dispatcher import Signal from app import signal_handlers import sys # import logging # logger = logging.getLogger(__name__) notification_via_sms = Signal(providing_args=["frm", "to", "message", "frm_alias"]) notification_via_sms.connect(signal_handlers.notify_via_sms)
from django.dispatch.dispatcher import Signal def create_app_structure_repeat_records(sender, application, **kwargs): from corehq.motech.repeaters.models import AppStructureRepeater domain = application.domain if domain: repeaters = AppStructureRepeater.by_domain(domain) for repeater in repeaters: repeater.register(application) app_post_save = Signal(providing_args=['application']) app_post_save.connect(create_app_structure_repeat_records) app_post_release = Signal(providing_args=['application'])
from tunga_tasks.models import Task, Application, Participation, ProgressEvent, ProgressReport, \ IntegrationActivity, Integration, Estimate, Quote, Sprint from tunga_tasks.notifications.email import notify_estimate_status_email, notify_task_invitation_email, \ send_task_application_not_selected_email, notify_payment_link_client_email from tunga_tasks.notifications.generic import notify_new_task, \ notify_task_approved, notify_new_task_admin, notify_task_invitation_response, notify_new_task_application, \ notify_task_application_response, notify_new_progress_report from tunga_tasks.notifications.slack import notify_new_progress_report_slack from tunga_tasks.tasks import initialize_task_progress_events, update_task_periodic_updates, \ create_or_update_hubspot_deal_task from tunga_utils import hubspot_utils from tunga_utils.constants import STATUS_SUBMITTED, STATUS_APPROVED, STATUS_DECLINED, \ STATUS_ACCEPTED, STATUS_REJECTED, STATUS_INITIAL # Task task_fully_saved = Signal(providing_args=["task", "new_user"]) task_approved = Signal(providing_args=["task"]) task_call_window_scheduled = Signal(providing_args=["task"]) task_details_completed = Signal(providing_args=["task"]) task_owner_added = Signal(providing_args=["task"]) task_applications_closed = Signal(providing_args=["task"]) task_closed = Signal(providing_args=["task"]) task_payment_approved = Signal(providing_args=["task"]) # Applications application_response = Signal(providing_args=["application"]) # Participation participation_response = Signal(providing_args=["participation"]) # Estimates
''' Created on Sep 1, 2012 @author: staticfish ''' from django.dispatch.dispatcher import Signal from workflow.views import post_attach_queue_save from tracker import views as tracker_views from tracker.models import WeekSnapshot from timeoff import views as timeoff_views from timeoff.models import BookTimeOff from overtime import views as overtime_views post_attach_queue_save_event = Signal(providing_args=['instance', 'is_draft']) post_attach_queue_save_event.connect(post_attach_queue_save, dispatch_uid='#weeksnapshot#') post_final_status_event = Signal(providing_args=['instance', 'status']) post_final_status_event.connect(tracker_views.post_final_status_update, sender=WeekSnapshot, dispatch_uid='#timeshet.weeksnapshot.approverqueue#') post_final_status_event.connect(overtime_views.weeksnapshot_post_final_status_update, sender=WeekSnapshot, dispatch_uid='#overtime.weeksnapshot.approverqueue#') post_final_status_event.connect(timeoff_views.post_final_status_update, sender=BookTimeOff, dispatch_uid='#booktimeoff.approverqueue#')
from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.dispatch.dispatcher import Signal from django.utils.encoding import python_2_unicode_compatible from json_field.fields import JSONField # @UnusedImport from api import fields, tasks from provider import import_provider_module # import user-defined configuration management module CM = importlib.import_module(settings.CM_MODULE) # define custom signals release_signal = Signal(providing_args=['user', 'app']) # base models class AuditedModel(models.Model): """Add created and updated fields to a model.""" created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: """Mark :class:`AuditedModel` as abstract.""" abstract = True
from casexml.apps.stock.models import StockTransaction from corehq.form_processor.models import FormArchiveRebuild from couchforms.signals import xform_archived, xform_unarchived def rebuild_form_cases(sender, xform, *args, **kwargs): from casexml.apps.case.xform import get_case_ids_from_form from casexml.apps.case.cleanup import rebuild_case_from_forms from corehq.form_processor.parsers.ledgers.form import get_case_ids_from_stock_transactions domain = xform.domain case_ids = get_case_ids_from_form( xform) | get_case_ids_from_stock_transactions(xform) detail = FormArchiveRebuild(form_id=xform.form_id, archived=xform.is_archived) for case_id in case_ids: rebuild_case_from_forms(domain, case_id, detail) xform_archived.connect(rebuild_form_cases) xform_unarchived.connect(rebuild_form_cases) # any time a case is saved case_post_save = Signal(providing_args=["case"]) # only when one or more cases are updated as the result of an xform submission # the contract of this signal is that you should modify the form and cases in # place but NOT save them. this is so that we can avoid multiple redundant writes # to the database in a row. we may want to revisit this if it creates problems. cases_received = Signal(providing_args=["xform", "cases"])
from tunga_activity import verbs from tunga_messages.models import Message from tunga_messages.tasks import get_or_create_task_channel from tunga_tasks.models import Task, Application, Participation, ProgressEvent, ProgressReport, \ IntegrationActivity, Integration, Estimate, Quote from tunga_tasks.notifications import notify_new_task_application, send_new_task_application_applicant_email, \ send_new_task_invitation_email, send_new_task_application_response_email, notify_task_invitation_response, \ send_task_application_not_selected_email, notify_new_progress_report, notify_task_approved, send_estimate_status_email from tunga_tasks.tasks import initialize_task_progress_events, update_task_periodic_updates, \ complete_harvest_integration from tunga_utils.constants import APP_INTEGRATION_PROVIDER_HARVEST, STATUS_SUBMITTED, STATUS_APPROVED, STATUS_DECLINED, \ STATUS_ACCEPTED, STATUS_REJECTED # Task task_approved = Signal(providing_args=["task"]) task_applications_closed = Signal(providing_args=["task"]) task_closed = Signal(providing_args=["task"]) # Applications application_response = Signal(providing_args=["application"]) # Participation participation_response = Signal(providing_args=["participation"]) # Estimates estimate_created = Signal(providing_args=["estimate"]) estimate_status_changed = Signal(providing_args=["estimate"]) # Quotes quote_created = Signal(providing_args=["quote"])
return try: domain_obj = Domain.get_by_name(application.domain) cc_config = domain_obj.call_center_config if not cc_config or not (cc_config.fixtures_are_active() and cc_config.config_is_valid()): return app_config = get_call_center_config_from_app(application) save = cc_config.update_from_app_config(app_config) if save: cc_config.save() except Exception: notify_exception(None, "Error updating CallCenter config for app build") def expire_latest_enabled_build_profiles(sender, application, **kwargs): if application.copy_of and toggles.RELEASE_BUILDS_PER_PROFILE.enabled(application.domain): for build_profile_id in application.build_profiles: get_latest_enabled_build_for_profile.clear(application.domain, build_profile_id) get_latest_enabled_versions_per_profile.clear(application.copy_of) app_post_save = Signal(providing_args=['application']) app_post_save.connect(create_app_structure_repeat_records) app_post_save.connect(update_callcenter_config) app_post_save.connect(expire_latest_enabled_build_profiles) app_post_release = Signal(providing_args=['application'])
from django.dispatch.dispatcher import Signal from django.utils.crypto import salted_hmac, constant_time_compare from django.conf import settings from powerapp.core import oauth from . import oauth_impl from powerapp.core.exceptions import PowerAppError from powerapp.core.web_utils import build_absolute_uri from django.utils.six.moves.urllib import parse logger = getLogger(__name__) CALENDAR_SUMMARY = 'Todoist Playground' if settings.DEBUG else 'Todoist' WEBHOOK_HMAC_SALT = 'gcal-webhooks' gcal_event_changed = Signal(providing_args=['integration', 'event']) gcal_event_deleted = Signal(providing_args=['integration', 'event_id']) def get_authorized_client(user): """ Return the Authorized requests session object """ client = oauth.get_client_by_name(oauth_impl.OAUTH_CLIENT_NAME) return client.get_oauth2_session(user) def get_or_create_todoist_calendar(integration): client = get_authorized_client(integration.user) resp = json_get(client, '/users/me/calendarList')
import yaml from celery.canvas import group from django.conf import settings from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver from django.dispatch.dispatcher import Signal from django.utils.encoding import python_2_unicode_compatible from api import fields from celerytasks import controller # define custom signals scale_signal = Signal(providing_args=['formation', 'user']) release_signal = Signal(providing_args=['formation', 'user']) def import_tasks(provider_type): """Return the celerytasks module for a provider. :param string provider_type: type of cloud provider **currently only "ec2"** :rtype: celerytasks module for the provider :raises: :py:class:`ImportError` if the provider isn't recognized """ try: tasks = importlib.import_module('celerytasks.' + provider_type) except ImportError as e: raise e return tasks
# coding: utf-8 from django.dispatch.dispatcher import Signal analyzer_default_format = Signal(providing_args=['value', 'category'])
parent_id = force_text(getattr(obj, field.attname)) else: parent_id = obj.pk try: parent_version = Version.objects.get(revision__id=self.revision_id, content_type=content_type, object_id=parent_id) except Version.DoesNotExist: pass else: result.update(parent_version.field_dict) setattr(self, "_field_dict_cache", result) return getattr(self, "_field_dict_cache") def revert(self): """Recovers the model in this version.""" self.object_version.save() def __str__(self): """Returns a unicode representation.""" return self.object_repr #Meta class Meta: app_label = 'reversion' # Version management signals. pre_revision_commit = Signal(providing_args=["instances", "revision", "versions"]) post_revision_commit = Signal(providing_args=["instances", "revision", "versions"])
from django.dispatch.dispatcher import Signal message_received = Signal()
from actstream.signals import action from django.db.models.signals import post_save from django.dispatch.dispatcher import receiver, Signal from tunga_activity import verbs from tunga_profiles.models import Connection, DeveloperApplication, Skill, DeveloperInvitation, UserProfile, UserRequest from tunga_profiles.notifications import send_new_developer_email, send_developer_accepted_email, \ send_developer_application_received_email, send_new_skill_email, send_developer_invited_email, \ notify_user_profile_updated_slack, notify_user_request_slack from tunga_profiles.tasks import sync_algolia_user from tunga_utils.constants import REQUEST_STATUS_ACCEPTED, STATUS_ACCEPTED, STATUS_REJECTED from tunga_utils.signals import post_nested_save user_profile_updated = Signal(providing_args=["profile"]) @receiver(post_nested_save, sender=UserProfile) def activity_handler_new_profile(sender, instance, created, **kwargs): if instance.user and instance.user.is_developer: sync_algolia_user.delay(instance.user.id) @receiver(post_save, sender=Connection) def activity_handler_new_connection(sender, instance, created, **kwargs): if created: action.send(instance.from_user, verb=verbs.CONNECT, action_object=instance, target=instance.to_user) else: update_fields = kwargs.get('update_fields', None)
from django.dispatch.dispatcher import Signal # Signal arguments: revision and versions pre_revision_commit = Signal() post_revision_commit = Signal()
from django.db import models as db from django.dispatch.dispatcher import Signal from django.dispatch import receiver from django.utils.translation import ugettext_lazy as _ from dj.choices import Choices from dj.choices.fields import ChoiceField from lck.django.common.models import MACAddressField, Named, TimeTrackable,\ WithConcurrentGetOrCreate from ralph.cmdb.models import CI from ralph.cmdb.models_audits import Auditable from ralph.discovery.models import Device # This signal is fired, when deployment is accepted in Bugtracker. # note, that you should manually change deployment statuses. deployment_accepted = Signal(providing_args=['deployment_id']) # Sanity checks - when Issue Tracker engine set to '', or some fields # are missing - fallback to NullIssueTracker engine NULL_ISSUE_TRACKER = False try: # engine is set? if settings.ISSUETRACKERS['default']['ENGINE']: ACTION_IN_PROGRESS = settings.ISSUETRACKERS['default']['OPA'][ 'ACTIONS']['IN_PROGRESS'] ACTION_IN_DEPLOYMENT = settings.ISSUETRACKERS['default']['OPA'][ 'ACTIONS']['IN_DEPLOYMENT'] ACTION_RESOLVED_FIXED = settings.ISSUETRACKERS['default']['OPA'][ 'ACTIONS']['RESOLVED_FIXED'] DEFAULT_ASSIGNEE = settings.ISSUETRACKERS['default']['OPA'][ 'DEFAULT_ASSIGNEE']
from notification_helper import * #from .models import notifications import json from django.dispatch.dispatcher import Signal invite_recieved = Signal(providing_args=["from", "to"]) def match(sender, **kwargs): """Trap the signal and do whatever is needed""" """ 1)create topic 2)subscribe sender_id,receiver_id to this topic 3)Publish message 4)delete topic *check if message goes when phone is switched off and i delete the topic """ from_user = kwargs['from'] to_user = kwargs['to'] topic = get_topic_arn("hello") #endpoint_sender = notifications.objects.get(user_id=sender_id).values_list('endpoint', flat=True) #endpoint_receiver = notifications.objects.get(user_id=receiver_id).values_list('endpoint', flat=True) subscribe_to_topic(TopicArn=topic, EndpointArn=create_platform_endpoint(token='APA91bEANg9ULweUM2eFbs1LHuDar3bF16aGb1uwsSufm9Eek6azzW1NoViRasFJ8Afla4FVSrVwlDoXlUG6e8F6kLxrPyOXHypM83CiB6VpQDBNtfOLNuX8SDmGtB18x3HZbxAcHx7_T7sDaZ99Z4LGdX_58blwa5qGySi9ewPBO7fi7CibA9U')) print topic #subscribe_to_topic(TopicArn=topic, EndpointArn=endpoint_receiver[0]) message = {'type':'match','users':[sender_id, receiver_id]} print message publish(TopicArn=topic, message=json.dumps(message)) delete_topic(topic) # Write to log, update db, send mail etc.