Added Scheduled task to get stats for template usage

Currently some pages are timing out due to the time it takes to perform
database queries. This is an attempt to improve the performance by
performing the query against the notification history table once a day
and use the notification table for a delta between midnight and the when
the page is run and combine the results.

- Added Celery task for doing the work
- Added a dao to handle the insert and update of the stats table
- Updated tests to test the new functionality
This commit is contained in:
Richard Chapman
2017-11-09 10:32:39 +00:00
parent ab43803453
commit ff911c30d6
8 changed files with 288 additions and 11 deletions

View File

@@ -1,7 +1,7 @@
import uuid
from datetime import date, datetime, timedelta
from datetime import date, datetime, timedelta, time
from sqlalchemy import asc, func
from sqlalchemy import asc, func, extract
from sqlalchemy.orm import joinedload
from flask import current_app
@@ -40,7 +40,7 @@ from app.models import (
)
from app.service.statistics import format_monthly_template_notification_stats
from app.statsd_decorators import statsd
from app.utils import get_london_month_from_utc_column, get_london_midnight_in_utc
from app.utils import get_london_month_from_utc_column, get_london_midnight_in_utc, get_london_year_from_utc_column
from app.dao.annual_billing_dao import dao_insert_annual_billing
DEFAULT_SERVICE_PERMISSIONS = [
@@ -520,3 +520,25 @@ def dao_fetch_active_users_for_service(service_id):
)
return query.all()
@statsd(namespace="dao")
def dao_fetch_monthly_historical_stats_by_template():
month = get_london_month_from_utc_column(NotificationHistory.created_at)
year = get_london_year_from_utc_column(NotificationHistory.created_at)
end_date = datetime.combine(date.today(), time.min)
return db.session.query(
NotificationHistory.template_id,
month.label('month'),
year.label('year'),
func.count().label('count')
).filter(
NotificationHistory.created_at < end_date
).group_by(
NotificationHistory.template_id,
month,
year
).order_by(
NotificationHistory.template_id
).all()

View File

@@ -0,0 +1,24 @@
from app import db
from app.models import StatsTemplateUsageByMonth
def insert_or_update_stats_for_template(template_id, month, year, count):
result = db.session.query(
StatsTemplateUsageByMonth
).filter(
StatsTemplateUsageByMonth.template_id == template_id,
StatsTemplateUsageByMonth.month == month,
StatsTemplateUsageByMonth.year == year
).update(
{
'count': count
}
)
if result == 0:
new_sms_sender = StatsTemplateUsageByMonth(
template_id=template_id,
month=month,
year=year,
count=count
)
db.session.add(new_sms_sender)