def handle(self, *args, **options): # noqa self.stdout.write("Démarrage de l'importation") dataset = options.get("dataset") verbose = options.get("verbose", False) if not dataset: raise CommandError("Identifiant du jeu de données à importer manquant") if dataset == "gendarmerie": results = importer.import_gendarmeries(verbose=verbose) elif dataset == "vaccination": results = importer.import_vaccination(verbose=verbose) elif dataset == "nestenn": results = importer.import_nestenn(verbose=verbose) else: raise CommandError(f"Identifiant de jeu de données inconnu: {dataset}") summary = build_summary(dataset, results) detailed_report = build_detailed_report(results) if verbose: print(detailed_report + "\n\n" + summary) mattermost.send( summary, attachements=[ { "pretext": "Détail des erreurs", "text": to_text_list(results["errors"]) if results["errors"] else "Aucune erreur rencontrée", } ], tags=[__name__], )
def test_send_simple(mocker): settings.MATTERMOST_HOOK = "http://fake" spy = mocker.spy(requests, "post") mattermost.send("foo", today=datetime(2021, 1, 1)) spy.assert_called_once_with( "http://fake", json={"text": "localhost — 01/01/2021 à 00:00:00: foo\n#production"}, )
def ping_mattermost(count): url = f"{settings.DATAGOUV_DOMAIN}/fr/datasets/acceslibre/" mattermost.send( "Export vers datagouv", attachements=[{ "pretext": "Aucune erreur rencontrée :thumbsup:", "text": f"- ERPs exportés: **{count}**\n[Lien vers le dataset]({url})", }], tags=[__name__], )
def handle(self, *args, **options): notifications = self.get_notifications() total = len(notifications) sent_ok = 0 for notification in notifications: sent_ok += 1 if self.send_notification(notification) else 0 if total > 0: plural = "s" if total > 1 else "" mattermost.send( f"{sent_ok}/{total} relance{plural} d'ERP{plural} non-publié{plural}", tags=[__name__], )
def handle(self, *args, **options): try: nb_deleted, _ = EmailToken.objects.filter( expire_at__lt=datetime.now(timezone.utc)).delete() if nb_deleted > 0: mattermost.send( f"{nb_deleted} jetons d'activation d'adresse email supprimés", tags=[__name__], ) except DatabaseError as err: raise CommandError( f"Erreur lors de la purge des jetons de changement d'adresse email: {err}" )
def start(self): print("Scheduler started") while True: try: schedule.run_pending() except CommandError as err: trace = traceback.format_exc() logger.error(err) mattermost.send( f"Erreur d'exécution de la commande: {err}", attachements=[{ "pretext": "Stack trace", "text": trace }], tags=[__name__], ) time.sleep(1)
def handle(self, *args, **options): if options["now"]: now = datetime.fromisoformat(options["now"]) else: now = timezone.now() notifications = self.get_notifications(options["hours"], now=now).values() total = len(notifications) sent_ok = 0 for notification in notifications: sent_ok += 1 if self.send_notification(notification) else 0 if total > 0: plural = "s" if total > 1 else "" mattermost.send( f"{sent_ok}/{total} notification{plural} de souscription envoyée{plural}", tags=[__name__], )
def handle(self, *args, **options): if options["today"]: today = datetime.fromisoformat(options["today"]) else: today = timezone.now() outdated_qs = (get_user_model().objects.annotate( erps_count=Count("erp")).filter( last_login=None, date_joined__lt=today - timedelta(days=options["days"]), erps_count=0, )) try: nb_deleted, _ = outdated_qs.delete() if nb_deleted > 0: mattermost.send( f"{nb_deleted} comptes utilisateur obsolètes supprimés.", tags=[__name__], ) except DatabaseError as err: raise CommandError( f"Erreur lors de la purge des comptes obslètes: {err}")