Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move mitxmako initialization to a startup module #811

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 0 additions & 25 deletions common/djangoapps/mitxmako/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,36 +12,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from mako.lookup import TemplateLookup
import tempdir
from django.template import RequestContext
from django.conf import settings

requestcontext = None
lookup = {}


class MakoMiddleware(object):
def __init__(self):
"""Setup mako variables and lookup object"""
# Set all mako variables based on django settings
template_locations = settings.MAKO_TEMPLATES
module_directory = getattr(settings, 'MAKO_MODULE_DIR', None)

if module_directory is None:
module_directory = tempdir.mkdtemp_clean()

for location in template_locations:
lookup[location] = TemplateLookup(directories=template_locations[location],
module_directory=module_directory,
output_encoding='utf-8',
input_encoding='utf-8',
default_filters=['decode.utf8'],
encoding_errors='replace',
)

import mitxmako
mitxmako.lookup = lookup

def process_request(self, request):
global requestcontext
Expand Down
8 changes: 4 additions & 4 deletions common/djangoapps/mitxmako/shortcuts.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from django.http import HttpResponse
import logging

from . import middleware
import mitxmako
from django.conf import settings
from django.core.urlresolvers import reverse
log = logging.getLogger(__name__)
Expand Down Expand Up @@ -80,15 +80,15 @@ def render_to_string(template_name, dictionary, context=None, namespace='main'):
context_instance['marketing_link'] = marketing_link

# In various testing contexts, there might not be a current request context.
if middleware.requestcontext is not None:
for d in middleware.requestcontext:
if mitxmako.middleware.requestcontext is not None:
for d in mitxmako.middleware.requestcontext:
context_dictionary.update(d)
for d in context_instance:
context_dictionary.update(d)
if context:
context_dictionary.update(context)
# fetch and render template
template = middleware.lookup[namespace].get_template(template_name)
template = mitxmako.lookup[namespace].get_template(template_name)
return template.render_unicode(**context_dictionary)


Expand Down
33 changes: 33 additions & 0 deletions common/djangoapps/mitxmako/startup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""
Initialize the mako template lookup
"""

import tempdir
from django.conf import settings
from mako.lookup import TemplateLookup

import mitxmako


def run():
"""Setup mako variables and lookup object"""
# Set all mako variables based on django settings
template_locations = settings.MAKO_TEMPLATES
module_directory = getattr(settings, 'MAKO_MODULE_DIR', None)

if module_directory is None:
module_directory = tempdir.mkdtemp_clean()

lookup = {}

for location in template_locations:
lookup[location] = TemplateLookup(
directories=template_locations[location],
module_directory=module_directory,
output_encoding='utf-8',
input_encoding='utf-8',
default_filters=['decode.utf8'],
encoding_errors='replace',
)

mitxmako.lookup = lookup
9 changes: 5 additions & 4 deletions common/djangoapps/mitxmako/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
from mako.template import Template as MakoTemplate
from mitxmako.shortcuts import marketing_link

from mitxmako import middleware
import mitxmako
import mitxmako.middleware

django_variables = ['lookup', 'output_encoding', 'encoding_errors']

Expand All @@ -33,7 +34,7 @@ class Template(MakoTemplate):
def __init__(self, *args, **kwargs):
"""Overrides base __init__ to provide django variable overrides"""
if not kwargs.get('no_django', False):
overrides = dict([(k, getattr(middleware, k, None),) for k in django_variables])
overrides = dict([(k, getattr(mitxmako, k, None),) for k in django_variables])
overrides['lookup'] = overrides['lookup']['main']
kwargs.update(overrides)
super(Template, self).__init__(*args, **kwargs)
Expand All @@ -47,8 +48,8 @@ def render(self, context_instance):
context_dictionary = {}

# In various testing contexts, there might not be a current request context.
if middleware.requestcontext is not None:
for d in middleware.requestcontext:
if mitxmako.middleware.requestcontext is not None:
for d in mitxmako.middleware.requestcontext:
context_dictionary.update(d)
for d in context_instance:
context_dictionary.update(d)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@

from student.models import UserProfile

import mitxmako.middleware as middleware

middleware.MakoMiddleware()


class Command(BaseCommand):
help = \
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@

from student.models import UserProfile

import mitxmako.middleware as middleware

middleware.MakoMiddleware()


def import_user(u):
user_info = u['u']
Expand Down
3 changes: 0 additions & 3 deletions common/djangoapps/student/management/commands/assigngroups.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User

import mitxmako.middleware as middleware
from student.models import UserTestGroup

import random
Expand All @@ -11,8 +10,6 @@
import json
from pytz import UTC

middleware.MakoMiddleware()


def group_from_value(groups, v):
''' Given group: (('a',0.3),('b',0.4),('c',0.3)) And random value
Expand Down
4 changes: 0 additions & 4 deletions common/djangoapps/student/management/commands/emaillist.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User

import mitxmako.middleware as middleware

middleware.MakoMiddleware()


class Command(BaseCommand):
help = \
Expand Down
8 changes: 3 additions & 5 deletions common/djangoapps/student/management/commands/massemail.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User

import mitxmako.middleware as middleware

middleware.MakoMiddleware()
import mitxmako


class Command(BaseCommand):
Expand All @@ -17,8 +15,8 @@ def handle(self, *args, **options):
#text = open(args[0]).read()
#subject = open(args[1]).read()
users = User.objects.all()
text = middleware.lookup['main'].get_template('email/' + args[0] + ".txt").render()
subject = middleware.lookup['main'].get_template('email/' + args[0] + "_subject.txt").render().strip()
text = mitxmako.lookup['main'].get_template('email/' + args[0] + ".txt").render()
subject = mitxmako.lookup['main'].get_template('email/' + args[0] + "_subject.txt").render().strip()
for user in users:
if user.is_active:
user.email_user(subject, text)
8 changes: 3 additions & 5 deletions common/djangoapps/student/management/commands/massemailtxt.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,13 @@
from django.core.management.base import BaseCommand
from django.conf import settings

import mitxmako.middleware as middleware
import mitxmako

from django.core.mail import send_mass_mail
import sys

import datetime

middleware.MakoMiddleware()


def chunks(l, n):
""" Yield successive n-sized chunks from l.
Expand Down Expand Up @@ -41,8 +39,8 @@ def handle(self, *args, **options):

users = [u.strip() for u in open(user_file).readlines()]

message = middleware.lookup['main'].get_template('emails/' + message_base + "_body.txt").render()
subject = middleware.lookup['main'].get_template('emails/' + message_base + "_subject.txt").render().strip()
message = mitxmako.lookup['main'].get_template('emails/' + message_base + "_body.txt").render()
subject = mitxmako.lookup['main'].get_template('emails/' + message_base + "_subject.txt").render().strip()
rate = int(ratestr)

self.log_file = open(logfilename, "a+", buffering=0)
Expand Down
3 changes: 0 additions & 3 deletions common/djangoapps/student/management/commands/userinfo.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User

import mitxmako.middleware as middleware
import json

from student.models import UserProfile

middleware.MakoMiddleware()


class Command(BaseCommand):
help = \
Expand Down
2 changes: 1 addition & 1 deletion common/lib/django_startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ def autostartup():
"""
for app in settings.INSTALLED_APPS:
try:
mod = import_module('{}.startup')
mod = import_module(app + '.startup')
if hasattr(mod, 'run'):
mod.run()
except ImportError:
Expand Down
9 changes: 0 additions & 9 deletions lms/djangoapps/certificates/queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from certificates.models import CertificateStatuses as status
from certificates.models import CertificateWhitelist

from mitxmako.middleware import MakoMiddleware
from courseware import grades, courses
from django.test.client import RequestFactory
from capa.xqueue_interface import XQueueInterface
Expand Down Expand Up @@ -52,14 +51,6 @@ class XQueueCertInterface(object):
"""

def __init__(self, request=None):
# MakoMiddleware Note:
# Line below has the side-effect of writing to a module level lookup
# table that will allow problems to render themselves. If this is not
# present, problems that a student hasn't seen will error when loading,
# causing the grading system to under-count the possible score and
# inflate their grade. This dependency is bad and was probably recently
# introduced. This is the bandage until we can trace the root cause.
m = MakoMiddleware()

# Get basic auth (username/password) for
# xqueue connection if it's in the settings
Expand Down
2 changes: 0 additions & 2 deletions lms/djangoapps/courseware/management/commands/check_course.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@

import xmodule

import mitxmako.middleware as middleware
middleware.MakoMiddleware()
from xmodule.modulestore.django import modulestore
from courseware.model_data import ModelDataCache
from courseware.module_render import get_module
Expand Down
5 changes: 5 additions & 0 deletions lms/djangoapps/courseware/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from student.models import CourseEnrollment
from student.tests.factories import AdminFactory
from mitxmako.middleware import MakoMiddleware

from xmodule.modulestore.django import modulestore

Expand Down Expand Up @@ -135,6 +136,10 @@ def test_about_blob_end_date(self):
def verify_end_date(self, course_id, expected_end_text=None):
request = self.request_factory.get("foo")
request.user = self.user

# TODO: Remove the dependency on MakoMiddleware (by making the views explicitly supply a RequestContext)
MakoMiddleware().process_request(request)

result = views.course_about(request, course_id)
if expected_end_text is not None:
self.assertContains(result, "Classes End")
Expand Down
21 changes: 0 additions & 21 deletions lms/djangoapps/instructor_task/tasks_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@

from xmodule.modulestore.django import modulestore

import mitxmako.middleware as middleware
from track.views import task_track

from courseware.models import StudentModule
Expand All @@ -35,26 +34,6 @@
UNKNOWN_TASK_ID = 'unknown-task_id'


def initialize_mako(sender=None, conf=None, **kwargs):
"""
Get mako templates to work on celery worker server's worker thread.

The initialization of Mako templating is usually done when Django is
initializing middleware packages as part of processing a server request.
When this is run on a celery worker server, no such initialization is
called.

To make sure that we don't load this twice (just in case), we look for the
result: the defining of the lookup paths for templates.
"""
if 'main' not in middleware.lookup:
TASK_LOG.info("Initializing Mako middleware explicitly")
middleware.MakoMiddleware()

# Actually make the call to define the hook:
worker_process_init.connect(initialize_mako)


class UpdateProblemModuleStateError(Exception):
"""
Error signaling a fatal condition while updating problem modules.
Expand Down