views.py 2.38 KB
Newer Older
1
# View for semi-static templatized content.
Piotr Mitros committed
2 3 4 5
#
# List of valid templates is explicitly managed for (short-term)
# security reasons.

6 7
import mimetypes

David Baumgold committed
8
from edxmako.shortcuts import render_to_response, render_to_string
9
from mako.exceptions import TopLevelLookupException
Piotr Mitros committed
10
from django.shortcuts import redirect
11
from django.conf import settings
12
from django.http import HttpResponseNotFound, HttpResponseServerError, Http404
13
from django.views.decorators.csrf import ensure_csrf_cookie
14

15
from util.cache import cache_if_anonymous
Piotr Mitros committed
16

17
valid_templates = []
18

19
if settings.STATIC_GRAB:
20 21 22 23 24
    valid_templates = valid_templates + [
        'server-down.html',
        'server-error.html'
        'server-overloaded.html',
    ]
Piotr Mitros committed
25

26 27

def index(request, template):
Piotr Mitros committed
28
    if template in valid_templates:
29
        return render_to_response('static_templates/' + template, {})
Piotr Mitros committed
30 31
    else:
        return redirect('/')
Piotr Mitros committed
32

33

34
@ensure_csrf_cookie
35
@cache_if_anonymous()
36 37 38 39 40
def render(request, template):
    """
    This view function renders the template sent without checking that it
    exists. Do not expose template as a regex part of the url. The user should
    not be able to ender any arbitray template name. The correct usage would be:
41

42
    url(r'^jobs$', 'static_template_view.views.render', {'template': 'jobs.html'}, name="jobs")
43
    """
44 45 46 47

    # Guess content type from file extension
    content_type, __ = mimetypes.guess_type(template)

48 49 50 51
    try:
        return render_to_response('static_templates/' + template, {}, content_type=content_type)
    except TopLevelLookupException:
        raise Http404
52

53

54
@ensure_csrf_cookie
55
@cache_if_anonymous()
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
def render_press_release(request, slug):
    """
    Render a press release given a slug.  Similar to the "render" function above,
    but takes a slug and does a basic conversion to convert it to a template file.
    a) all lower case,
    b) convert dashes to underscores, and
    c) appending ".html"
    """
    template = slug.lower().replace('-', '_') + ".html"
    try:
        resp = render_to_response('static_templates/press_releases/' + template, {})
    except TopLevelLookupException:
        raise Http404
    else:
        return resp


73
def render_404(request):
74
    return HttpResponseNotFound(render_to_string('static_templates/404.html', {}, request=request))
75 76


77
def render_500(request):
78
    return HttpResponseServerError(render_to_string('static_templates/server-error.html', {}, request=request))