website/www/conservancy/static/views.py
Brett Smith a00195c8f6 static.views: Deduplicate code.
The primary goal here is to get templates rendered more like our "regular"
templates, by using more of the standard tools to do so rather than roll our
own.

* Use TemplateResponse. This requires less boilerplate and ensures the
  rendering runs through our local context processors.
* Use the existing definition of fundgoal_lookup.
2018-11-20 11:58:34 -05:00

58 lines
1.9 KiB
Python

import mimetypes
import os.path
from django.http import HttpResponse
from django.template.response import TemplateResponse
from conservancy.apps.fundgoal.models import FundraisingGoal
from conservancy.local_context_processors import fundgoal_lookup
STATIC_ROOT = os.path.abspath(os.path.dirname(__file__))
FILESYSTEM_ENCODING = 'utf-8'
def handler(request, errorcode):
path = os.path.join('error', str(errorcode), 'index.html')
fullpath = os.path.join(STATIC_ROOT, path)
if not os.path.exists(fullpath):
return HttpResponse("Internal error: " + path, status=int(errorcode))
else:
return TemplateResponse(request, path, status=int(errorcode))
def handler401(request):
return handler(request, 401)
def handler403(request):
return handler(request, 403)
def handler404(request):
return handler(request, 404)
def handler500(request):
return handler(request, 500)
def index(request, *args, **kwargs):
path = request.path.lstrip(u'/')
if path.endswith(u'/'):
path += u'index.html'
try:
path_bytes = path.encode(FILESYSTEM_ENCODING)
except UnicodeEncodeError:
# If the path can't be expressed on the filesystem, it must not exist.
return handler404(request)
fullpath = os.path.join(STATIC_ROOT, path_bytes)
if not os.path.exists(fullpath):
return handler404(request)
content_type, _ = mimetypes.guess_type(path)
if content_type != 'text/html':
return HttpResponse(open(fullpath, 'rb'), content_type)
else:
context = kwargs.copy()
try:
context['fundgoal'] = fundgoal_lookup(kwargs['fundraiser_sought'])
except KeyError:
pass
return TemplateResponse(request, path, context)
def debug(request):
path = request.get_full_path()
path = path.lstrip('/')
return HttpResponse("Hello, static world: " + path)