Skip to content

Instantly share code, notes, and snippets.

@mariocesar
Last active November 5, 2015 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariocesar/1d8d44987a1cd8b0124b to your computer and use it in GitHub Desktop.
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.
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)
PUBLIC_ROOT = '/var/www/html'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment