-
Notifications
You must be signed in to change notification settings - Fork 8
/
flowers.py
85 lines (59 loc) · 2.47 KB
/
flowers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python
# encoding: utf-8
"""
Send email to a loved one to encourage them to make a small gesture of love.
Run this code as a once-daily cron task. It will randomly pick a day of the
month to send an email to your loved one, telling them to buy you flowers.
"""
import datetime
import calendar
import random
import os
import json
from mailer import send_email
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
FLOWERDATE_FILE = os.path.join(PROJECT_ROOT, 'flowerdate.json')
def write_flowermap(day, month, email_sent):
flowermap = {'flowerday': day,
'current_month': month,
'email_sent': email_sent}
with open(FLOWERDATE_FILE, 'w') as f:
f.write(json.dumps(flowermap))
return flowermap
def load_or_create_flowermap():
"""Read flowermap file if it exists; generate flowermap if it does not."""
if not os.path.isfile(FLOWERDATE_FILE):
flowermap = write_flowermap(None, None, False)
else:
with open(FLOWERDATE_FILE, 'r') as f:
flowermap = json.loads(f.read())
return flowermap
def check_date_for_emailer(flowermap, todays_date):
"""Use flowermap to figure out if today is the day to send the email."""
email_sent = False
# if today's date matches this month's generated date, run emailer
if flowermap['flowerday'] <= todays_date.day and \
flowermap['current_month'] <= todays_date.month and \
not flowermap['email_sent']:
email_sent = True
send_email()
write_flowermap(todays_date.day, todays_date.month, email_sent)
return email_sent
def generate_date(flowermap, todays_date):
"""Check whether we should generate a new date; if so, run generator."""
generated_flowermap = False
if not flowermap['flowerday'] or flowermap['current_month'] != todays_date.month:
_, ndays = calendar.monthrange(todays_date.year, todays_date.month)
flowerday = random.choice(range(1, ndays + 1))
# print 'flowerday is...',flowerday
recentmonth = todays_date.month
# print 'recent month is...', recentmonth
flowermap = write_flowermap(flowerday, recentmonth, False)
generated_flowermap = True
return flowermap, generated_flowermap
def main(todays_date):
flowermap = load_or_create_flowermap()
flowermap = generate_date(flowermap, todays_date)[0]
check_date_for_emailer(flowermap, todays_date)
if __name__ == '__main__':
main(datetime.date.today())