Coverage for portality / tasks / site_statistics.py: 49%

37 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-05-04 09:41 +0100

1from portality import models 

2from portality.background import BackgroundTask, BackgroundApi 

3from portality.bll.doaj import DOAJ 

4from portality.core import app 

5from portality.tasks.helpers import background_helper 

6from portality.tasks.redis_huey import scheduled_short_queue as queue 

7 

8import json 

9 

10 

11class SiteStatisticsBackgroundTask(BackgroundTask): 

12 

13 __action__ = "site_statistics" 

14 

15 def run(self): 

16 """ 

17 Execute the task as specified by the background_job  

18 :return: 

19 """ 

20 job = self.background_job 

21 siteSvc = DOAJ.siteService() 

22 

23 job.add_audit_message("Starting Site Stats Cache Update") 

24 new_stats = siteSvc.cache_site_statistics() 

25 job.add_audit_message("Site Stats Cache Updated: {stats}".format(stats=json.dumps(new_stats, indent=2))) 

26 

27 def cleanup(self): 

28 """ 

29 Cleanup after a successful OR failed run of the task 

30 :return: 

31 """ 

32 pass 

33 

34 @classmethod 

35 def prepare(cls, username, **kwargs): 

36 """ 

37 Take an arbitrary set of keyword arguments and return an instance of a BackgroundJob, 

38 or fail with a suitable exception 

39 

40 :param kwargs: arbitrary keyword arguments pertaining to this task type 

41 :return: a BackgroundJob instance representing this task 

42 """ 

43 # prepare a job record 

44 params = {} 

45 job = background_helper.create_job(username, cls.__action__, queue_id=huey_helper.queue_id, params=params) 

46 return job 

47 

48 @classmethod 

49 def submit(cls, background_job): 

50 """ 

51 Submit the specified BackgroundJob to the background queue 

52 

53 :param background_job: the BackgroundJob instance 

54 :return: 

55 """ 

56 background_job.save() 

57 site_statistics.schedule(args=(background_job.id,), delay=app.config.get('HUEY_ASYNC_DELAY', 10)) 

58 

59 

60huey_helper = SiteStatisticsBackgroundTask.create_huey_helper(queue) 

61 

62 

63@huey_helper.register_schedule 

64def scheduled_site_statistics(): 

65 user = app.config.get("SYSTEM_USERNAME") 

66 job = SiteStatisticsBackgroundTask.prepare(user) 

67 SiteStatisticsBackgroundTask.submit(job) 

68 

69 

70@huey_helper.register_execute(is_load_config=False) 

71def site_statistics(job_id): 

72 job = models.BackgroundJob.pull(job_id) 

73 task = SiteStatisticsBackgroundTask(job) 

74 BackgroundApi.execute(task)