Avoid depending on app context when templating failure reports (#4231)

* don't need to depend on context when templating failure reports

* extract a render_template function with some docs

* CodeClimate has really outdone itself this time. Removed a whitespace character in order to fix 2 CodeClimate errors

* apparently whitespace doesn't count as a character
This commit is contained in:
Omer Lachish 2019-10-15 23:08:28 +03:00 committed by GitHub
parent 27cd76797e
commit f6e1470a7c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 13 additions and 5 deletions

View File

@ -1,11 +1,10 @@
import datetime
import re
from collections import Counter
from flask import render_template
from redash.tasks.general import send_mail
from redash.worker import celery
from redash import redis_connection, settings, models
from redash.utils import json_dumps, json_loads, base_url
from redash.utils import json_dumps, json_loads, base_url, render_template
def key(user_id):
@ -50,9 +49,9 @@ def send_failure_report(user_id):
'base_url': base_url(user.org)
}
html = render_template('emails/failures.html', **context)
text = render_template('emails/failures.txt', **context)
subject = "Redash failed to execute {} of your scheduled queries".format(len(unique_errors.keys()))
html, text = [render_template('emails/failures.{}'.format(f), context) for f in ['html', 'txt']]
send_mail.delay([user.email], subject, html, text)
redis_connection.delete(key(user_id))

View File

@ -15,6 +15,7 @@ from six import string_types
import pystache
import pytz
import simplejson
from flask import current_app
from funcy import select_values
from redash import settings
from sqlalchemy.orm.query import Query
@ -205,3 +206,11 @@ def deprecated():
return K
return wrapper
def render_template(path, context):
""" Render a template with context, without loading the entire app context.
Using Flask's `render_template` function requires the entire app context to load, which in turn triggers any
function decorated with the `context_processor` decorator, which is not explicitly required for rendering purposes.
"""
current_app.jinja_env.get_template(path).render(**context)

View File

@ -26,7 +26,7 @@ class TestSendAggregatedErrorsTask(BaseTestCase):
def send_email(self, user, render_template):
send_failure_report(user.id)
_, context = render_template.call_args
_, context = render_template.call_args[0]
return context['failures']
def test_schedules_email_if_failure_count_is_beneath_limit(self):