Last active
November 5, 2015 01:32
-
-
Save mariocesar/1d8d44987a1cd8b0124b to your computer and use it in GitHub Desktop.
Django Middleware to serve a root if no file is found then serve the django, this intended to be use with the $tryfile option in nginx.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from os import path | |
from django.conf import settings | |
from django.http import Http404 | |
from django.views import static | |
class TryStatic: | |
def __init__(self): | |
self.root = settings.PUBLIC_ROOT | |
self.index_file = 'index.html' | |
def process_response(self, request, response): | |
if not settings.DEBUG: | |
return response | |
if response.status_code != 404: | |
return response # No need to check for a flatpage for non-404 responses. | |
try: | |
return self.serve_pathinfo(request, request.path_info) | |
# Return the original response if any errors happened. Because this | |
# is a middleware, we can't assume the errors will be caught elsewhere. | |
except Http404: | |
return response | |
except Exception: | |
if settings.DEBUG: | |
raise | |
return response | |
def serve_pathinfo(self, request, path_info): | |
if path_info[-1] == '/': | |
path_info = path_info + self.index_file | |
return static.serve(request, path=path_info, document_root=self.root, show_indexes=False) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PUBLIC_ROOT = '/var/www/html' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment