|
1
|
|
|
# coding=utf-8 |
|
2
|
|
|
""" |
|
3
|
|
|
Roughpage views |
|
4
|
|
|
""" |
|
5
|
|
|
__author__ = 'Alisue <[email protected]>' |
|
6
|
|
|
import os |
|
7
|
|
|
from django.http import Http404, HttpResponse |
|
8
|
|
|
from django.template import loader, RequestContext, TemplateDoesNotExist |
|
9
|
|
|
from django.shortcuts import redirect |
|
10
|
|
|
from django.views.decorators.csrf import csrf_protect |
|
11
|
|
|
from roughpages.conf import settings |
|
12
|
|
|
from roughpages.backends import get_backend |
|
13
|
|
|
from roughpages.utils import url_to_filename |
|
14
|
|
|
|
|
15
|
|
|
# This view is called from RoughpageFallbackMiddleware.process_response |
|
16
|
|
|
# when a 404 is raised, which often means CsrfViewMiddleware.process_view |
|
17
|
|
|
# has not been called even if CsrfViewMiddleware is installed. So we need |
|
18
|
|
|
# to use @csrf_protect, in case the template needs {% csrf_token %}. |
|
19
|
|
|
# However, we can't just wrap this view; if no matching roughpage exists, |
|
20
|
|
|
# or a redirect is required for authentication, the 404 needs to be returned |
|
21
|
|
|
# without any CSRF checks. Therefore, we only |
|
22
|
|
|
# CSRF protect the internal implementation. |
|
23
|
|
|
|
|
24
|
|
|
|
|
25
|
|
|
def roughpage(request, url): |
|
26
|
|
|
""" |
|
27
|
|
|
Public interface to the rough page view. |
|
28
|
|
|
""" |
|
29
|
|
|
if settings.APPEND_SLASH and not url.endswith('/'): |
|
30
|
|
|
# redirect to the url which have end slash |
|
31
|
|
|
return redirect(url + '/', permanent=True) |
|
32
|
|
|
# get base filename from url |
|
33
|
|
|
filename = url_to_filename(url) |
|
34
|
|
|
# try to find the template_filename with backends |
|
35
|
|
|
template_filenames = get_backend().prepare_filenames(filename, |
|
36
|
|
|
request=request) |
|
37
|
|
|
# add extra prefix path |
|
38
|
|
|
root = settings.ROUGHPAGES_TEMPLATE_DIR |
|
39
|
|
|
template_filenames = [os.path.join(root, x) for x in template_filenames] |
|
40
|
|
|
try: |
|
41
|
|
|
t = loader.select_template(template_filenames) |
|
42
|
|
|
return render_roughpage(request, t) |
|
43
|
|
|
except TemplateDoesNotExist: |
|
44
|
|
|
if settings.ROUGHPAGES_RAISE_TEMPLATE_DOES_NOT_EXISTS: |
|
45
|
|
|
raise |
|
46
|
|
|
raise Http404 |
|
47
|
|
|
|
|
48
|
|
|
|
|
49
|
|
|
@csrf_protect |
|
50
|
|
|
def render_roughpage(request, t): |
|
51
|
|
|
""" |
|
52
|
|
|
Internal interface to the rough page view. |
|
53
|
|
|
""" |
|
54
|
|
|
import django |
|
55
|
|
|
if django.VERSION >= (1, 8): |
|
56
|
|
|
c = {} |
|
57
|
|
|
response = HttpResponse(t.render(c, request)) |
|
58
|
|
|
else: |
|
59
|
|
|
c = RequestContext(request) |
|
60
|
|
|
response = HttpResponse(t.render(c)) |
|
61
|
|
|
return response |
|
62
|
|
|
|