def update_model(self, allow_fail=False): from django_joblog.models import db_alias with transaction.atomic(using=db_alias()): model = self._get_model(allow_fail=allow_fail) if not model and allow_fail: return now = timezone.now() duration = now - model.date_started model.log_text = self._p.get_log_text() model.error_text = self._p.get_error_text() model.duration = duration model.save(using=db_alias())
def _finish(self, exception_or_error=None): from django_joblog.models import db_alias, JobLogStates model = self._get_model() model.date_ended = timezone.now() model.duration = model.date_ended - model.date_started model.state = JobLogStates.finished.name if exception_or_error is not None: if model.error_text: model.error_text = "%s\n%s" % (model.error_text, exception_or_error) else: model.error_text = "%s" % exception_or_error model.state = JobLogStates.error.name model.save(using=db_alias()) if self._p.print_to_console: if model.log_text or model.error_text: print("\n---summary---") if model.log_text: print("LOG:\n%s" % model.log_text) if model.error_text: print("ERROR:\n%s" % model.error_text) print("%s.%s finished after %s" % (model.name, model.count, model.duration))
def test_no_parallel(self): def _task(): with JobLogger("test-no-parallel") as log: time.sleep(1) log.log("Great!") thread = Thread(target=_task) thread.start() time.sleep(0.1) try: with self.assertRaises(JobIsAlreadyRunningError): with JobLogger("test-no-parallel") as log: log.log("try to run in parallel") qset = JobLogModel.objects.using( db_alias()).filter(name="test-no-parallel") self.assertEqual( 1, qset.filter(state=JobLogStates.running.name).count()) self.assertEqual( 1, qset.filter(state=JobLogStates.blocked.name).count()) finally: thread.join()
def test_parallel(self): def _task(): with JobLogger("test-parallel", parallel=True) as log: time.sleep(1) log.log("Great!") threads = [] for i in range(3): threads.append(Thread(target=_task)) threads[-1].start() for t in threads: t.join() self.assertEqual( 3, JobLogModel.objects.using( db_alias()).filter(name="test-parallel").count())
def handle(self, *args, **options): try: job = JobLogModel.objects.using(db_alias()).get(pk=options["pk"]) for n in ( "name", "count", "date_started", "date_ended", "duration", "state", ): print("%12s: %s" % (n, getattr(job, n))) if job.log_text: print("log:") print(job.log_text) if job.error_text: print("error:") print(job.error_text) except JobLogModel.DoesNotExist: print("Unknown pk '%s'" % options["pk"])
def finish(self, error_text=None): from django_joblog.models import db_alias if self._model_pk is not None: with transaction.atomic(using=db_alias()): self._finish(error_text)
def manager(self): from django_joblog.models import JobLogModel, db_alias return JobLogModel.objects.using(db_alias())
def manager(): return JobLogModel.objects.using(db_alias())