Coverage for src/template.py: 42%

50 statements  

« prev     ^ index     » next       coverage.py v7.3.0, created at 2024-10-10 12:25 +0000

1import random 

2 

3import jinja2 

4 

5 

6template_loader = jinja2.FileSystemLoader(searchpath='./templates') 

7template_env = jinja2.Environment(loader=template_loader) 

8 

9 

10def register(func): 

11 template_env.globals[func.__name__] = func 

12 

13 

14def render_template(template_name: str, context={}): 

15 """ 

16 Render a template into a string. 

17 """ 

18 template = template_env.get_template(template_name) 

19 return template.render(**context) 

20 

21 

22@register 

23def on_this_date(today, entries): 

24 def same_date(e): 

25 same_month = e.date.month == today.month 

26 same_day = e.date.day == today.day 

27 different_year = e.date.year != today.year 

28 return same_month and same_day and different_year 

29 

30 matching = filter(same_date, entries) 

31 

32 try: 

33 return random.choice(list(matching)) 

34 except IndexError: 

35 return None 

36 

37 

38@register 

39def find_random_napkin(images): 

40 try: 

41 return random.choice([i for i in images if 'napkin' in (i.slug or '')]) 

42 except IndexError: 

43 return None 

44 

45 

46@register 

47def find_random_entry_with_banner(entries): 

48 return random.choice([e for e in entries if e.banner]) 

49 

50 

51@register 

52def find_napkins(images): 

53 def is_napkin(image): 

54 return 'napkin' in (image.slug or '') 

55 

56 napkins = list(filter(is_napkin, images)) 

57 group_by = 3 

58 return [napkins[i:i + group_by] for i in range(0, len(napkins), group_by)] 

59 

60 

61@register 

62def find_looking_back_entries(entries): 

63 return [e for e in entries if e.description.startswith('looking back on')] 

64 

65 

66@register 

67def find_homework(entries): 

68 def is_homework(e): 

69 return e.description.startswith('from the homework vault:') 

70 

71 return list(filter(is_homework, entries)) 

72 

73 

74@register 

75def find_anti_journals(entries): 

76 def is_anti(e): 

77 return e.description.startswith('anti-journal') 

78 

79 return list(filter(is_anti, entries))