123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- from datetime import datetime, timedelta
- from django.core.mail import send_mail
- from django.template import Template, Context
- from django.http import HttpResponse
- from django.conf import settings
- from .models import ScheduledReport, ScheduledReportGroup, ReportRecipient
- class ScheduledReportConfig(object):
- def __init__(self, scheduled_report):
- """
- Expects a scheduled report object and inititializes
- its own scheduled_report attribute with it
- """
- self.scheduled_report = scheduled_report
- def get_report_config(self):
- """
- Returns the configuration related to a scheduled report, needed
- to populate the email
- """
- return {
- "template_context": self._get_related_reports_data(),
- "recipients": self._get_report_recipients()
- }
- def _get_related_reports_data(self):
- """
- Returns the list of reports data which needs to be sent out in a scheduled report
- """
- pass
- def _get_report_recipients(self):
- """
- Returns the recipient list for a scheduled report
- """
- pass
- def create_email_data(content=None):
- content = '''
-
-
- ''' + str(content) + ''''''
- return content
- def send_emails():
- current_time = datetime.utcnow()
- scheduled_reports = ScheduledReport.objects.filter(next_run_at__lt = current_time)
- for scheduled_report in scheduled_reports:
- report_config = ScheduledReportConfig(scheduled_report).get_report_config()
- """ Specify the template path you want to send out in the email. """
- template = Template(create_email_data('path/to/your/email_template.html'))
- """ //Create your email html using Django's context processor """
- report_template = template.render(Context(report_config['template_context']))
- scheduled_report.save()
- if not scheduled_report.subject:
- """ Handle exception for subject not provided """
- if not report_config['recipients']:
- """ Handle exception for recipients not provided """
- send_mail(
- scheduled_report.subject, 'Here is the message.',
- settings.EMAIL_HOST_USER, report_config['recipients'],
- fail_silently=False, html_message=report_template
- )
|