Best Python code snippet using slash
errorhandler.py
Source:errorhandler.py  
...4    def __init__(self, factory):5        self._factory = factory6        self._format_kwargs = {}7    def raise_error(self, error_code, *params):8        self.create_format_kwargs(error_code, params)9        msg_header = self.create_header(error_code, params[0])10        msg_body = self.create_error_body(error_code)11        raise EventsFactoryError(msg_header + msg_body)12    def create_format_kwargs(self, error_code, params):13        """14        param_keys = {15            'CLASS OVERWRITE': ('events_class', 'class_keys', 'class_args_tuple'),16            'MISSING GETTER': ('events_class', 'current_getters', 'getter_key'),17            'GETTER OVERWRITE': ('getter_key', 'factory_getter', 'new_getter'),18            'SIGNATURES DIFFERENT': ('events_class', 'signature_in_factory'),19            'WTF': ('events_class', 'factory_classes')20        }21        """22        self._assign_parameters(error_code, params)23        self._assign_kwargs_from_factory_class()24    def _assign_parameters(self, error_code, params):25        param_values = {26            'CLASS OVERWRITE': ('events_class', 'class_args_tuple'),...notifier.py
Source:notifier.py  
...20        pass21    @abstractmethod22    def notify_end(self, message=None, **kwargs):23        pass24    def _format_kwargs(self, kwargs):25        return "\n".join([f"{k}:  {v}" for k, v in kwargs.items()])26    def _get_run_time(self):27        if self.start_time and self.end_time:28            elapsed = self.end_time - self.start_time29            elapsed -= datetime.timedelta(microseconds=elapsed.microseconds)30            return f"\n\nStarted: {self.start_time:%Y-%m-%d %H:%M:%S}\nEnded: {self.end_time:%Y-%m-%d %H:%M:%S}\nRun time: {elapsed}"31        elif self.start_time:32            return f"\n\nStarted: {self.start_time:%Y-%m-%d %H:%M:%S}"33        else:34            return ""35class TelegramNotifier(Notifier):36    name = "telegram"37    def __init__(self, recipients: List[str] = None, title=None):38        super().__init__(title=title)39        self.recipients = recipients40        self.telegram = Telegram(parse_mode=ParseMode.HTML)41    def notify_start(self, message=None, **kwargs):42        self.start_time = datetime.datetime.now()43        title = " Started: " + self.title44        text = self.telegram.format_fixed(self._format_kwargs(kwargs))45        if message:46            text = message + "\n" + text47        text += self._get_run_time()48        if self.recipients:49            for recipient in self.recipients:50                self.telegram.send_message(text, title=title, chat_id=recipient, icon=START_ICON)51        else:52            self.telegram.send_message(text, title=title, icon=START_ICON)53    def notify_error(self, error_message):54        self.end_time = datetime.datetime.now()55        title = "FAILED: " + self.title56        text = error_message + self._get_run_time()57        if self.recipients:58            for recipient in self.recipients:59                self.telegram.send_message(text, title=title, chat_id=recipient, icon=ERROR_ICON)60        else:61            self.telegram.send_message(text, title=title, icon=ERROR_ICON)62    def notify_end(self, message=None, **kwargs):63        self.end_time = datetime.datetime.now()64        title = "Finished: " + self.title65        text = self.telegram.format_fixed(self._format_kwargs(kwargs))66        if message:67            text = message + "\n" + text68        text += self._get_run_time()69        if self.recipients:70            for recipient in self.recipients:71                self.telegram.send_message(text, title=title, chat_id=recipient, icon=END_ICON)72        else:73            self.telegram.send_message(text, title=title, icon=END_ICON)74class EmailNotifier(Notifier):75    name = "email"76    def __init__(self, recipients: List[str], sender: str = None, title=None):77        super().__init__(title=title)78        self.recipients = recipients79        self.mail_sender = yagmail.SMTP(user=sender)80    def notify_start(self, message=None, **kwargs):81        self.start_time = datetime.datetime.now()82        title = START_ICON + " Started: " + self.title83        text = self._format_kwargs(kwargs)84        if message:85            text = message + "\n" + text86        text += self._get_run_time()87        for recipient in self.recipients:88            self.mail_sender.send(to=recipient, subject=title, contents=text)89    def notify_error(self, error_message):90        self.end_time = datetime.datetime.now()91        title = ERROR_ICON + " FAILED: " + self.title92        for recipient in self.recipients:93            self.mail_sender.send(to=recipient, subject=title, contents=error_message + self._get_run_time())94    def notify_end(self, message=None, **kwargs):95        self.end_time = datetime.datetime.now()96        title = END_ICON + " Finished: " + self.title97        text = self._format_kwargs(kwargs)98        if message:99            text = message + "\n" + text100        text += self._get_run_time()101        for recipient in self.recipients:102            self.mail_sender.send(to=recipient, subject=title, contents=text)103NOTIFIER_CLASSES = {}104for name, obj in globals().copy().items():105    if inspect.isclass(obj) and issubclass(obj, Notifier) and obj != Notifier:...backends.py
Source:backends.py  
1from string import Formatter2from django.core.mail import send_mail3from django.contrib.contenttypes.models import ContentType4from subscription.models import Subscription5class BaseBackend(object):6    def __call__(obj,*args,**kwargs):7        return obj.emit(*args,**kwargs)8    def emit(self,text,subscribers_of=None,dont_send_to=None,send_only_to=None,actor=None,\9        actor_display_other=None,actor_display_self=None,format_kwargs=None,**kwargs):10        # subscribers_of - Thing people are subscribed to11        # dont_send_to / send_only_to - useful maybe?12        # text - string you want to emit.13        # actor_display_other - How does the actor appear to others? <a href="">{{ user.username }}</a>14        # actor_display_self - How does the actor appear to self? aka "You"15        # format_kwargs - Will be applied to text a la: text.format(**format_kwargs)16        # **kwargs - Maybe you wrote a backend that wants more stuff than the above!!17        # CAREFUL: If you send a typo-kwarg it will just be sent to emit(), so no error will raise =(18        self.kwargs = kwargs19        explicit_format_options = [i[1] for i in Formatter().parse(text)]20        if not subscribers_of:21            for recipient in send_only_to:22                self.emit(recipient,text,**kwargs)23            return24        self.content_type = ContentType.objects.get_for_model(subscribers_of)25        subscription_kwargs = {'content_type': self.content_type, 'object_id': subscribers_of.pk}26        if send_only_to:27            subscription_kwargs.update({'user__in': send_only_to})28        for i in Subscription.objects.filter(**subscription_kwargs):29            if i.user in (dont_send_to or []):30                continue31            if send_only_to and i.user not in send_only_to:32                continue33            _format_kwargs = {}34            _format_kwargs.update(format_kwargs or {})35            display_text = "%s" % text36            if "actor" in explicit_format_options:37                _format_kwargs.update({'actor': actor_display_other})38                if i.user == actor:39                    _format_kwargs.update({'actor': actor_display_self})40            text = text.format(**_format_kwargs) # Emit, somehow.41            self.emit(i.user,text,**kwargs)42    def user_emit(self,user,text,**kwargs):43        raise NotImplementedError("Override this!")44class SimpleEmailBackend(BaseBackend):45    def user_emit(self,user,text,**kwargs):46        if not user.email:47            return48        send_mail(self.get_subject(),text,None,[user.email])49    def get_subject(self):...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
