def serve(request, path, show_indexes=False): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: (r'^(?P<path>.*)$', 'staticfiles.views.serve') in your URLconf. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index``. """ # Clean up given path to only allow serving files below document_root. path = posixpath.normpath(urllib.unquote(path)) path = path.lstrip("/") newpath = "" for part in path.split("/"): if not part: # Strip empty path components. continue drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): # Strip '.' and '..' in path. continue newpath = os.path.join(newpath, part).replace("\\", "/") if newpath and path != newpath: return HttpResponseRedirect(newpath) newpath = newpath.encode("utf-8") fullpath = get_media_path(newpath) if fullpath is None: raise Http404, '"%s" does not exist' % newpath if not os.path.exists(fullpath): raise Http404, '"%s" does not exist' % fullpath if os.path.isdir(fullpath): if show_indexes: return directory_index(newpath, fullpath) raise Http404, "Directory indexes are not allowed here." # Respect the If-Modified-Since header. statobj = os.stat(fullpath) if not was_modified_since( request.META.get("HTTP_IF_MODIFIED_SINCE"), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE] ): return HttpResponseNotModified() mimetype = mimetypes.guess_type(fullpath)[0] or "application/octet-stream" contents = open(fullpath, "rb").read() response = HttpResponse(mimetype=mimetype) response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) response["Content-Length"] = len(contents) # lighttpd only lighttpd_path = get_webserver_path(newpath) response["X-Sendfile"] = lighttpd_path new_filename = fullpath.split("/")[-1] new_filename = new_filename.replace(" ", "_") response["Content-Disposition"] = "attachment;filename=%s" % new_filename return response
def serve(request, path, document_root=None, show_indexes=False): """ Note: Modified to use X-Sendfile Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: from django.views.static import serve url(r'^(?P<path>.*)$', serve, {'document_root': '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(unquote(path)).lstrip("/") fullpath = safe_join(document_root, path) if os.path.isdir(fullpath): if show_indexes: return directory_index(path, fullpath) raise Http404("Directory indexes are not allowed here.") if not os.path.exists(fullpath): raise Http404('"%(path)s" does not exist' % {"path": fullpath}) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) if not was_modified_since( request.META.get("HTTP_IF_MODIFIED_SINCE"), statobj.st_mtime, statobj.st_size ): return HttpResponseNotModified() response = HttpResponse() response["X-Sendfile"] = fullpath return response
def serve(request, path, show_indexes=False): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: (r'^(?P<path>.*)$', 'staticfiles.views.serve') in your URLconf. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index``. """ # Clean up given path to only allow serving files below document_root. path = posixpath.normpath(urllib.unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not part: # Strip empty path components. continue drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): # Strip '.' and '..' in path. continue newpath = os.path.join(newpath, part).replace('\\', '/') if newpath and path != newpath: return HttpResponseRedirect(newpath) newpath = newpath.encode('utf-8') fullpath = get_media_path(newpath) if fullpath is None: raise Http404, '"%s" does not exist' % newpath if not os.path.exists(fullpath): raise Http404, '"%s" does not exist' % fullpath if os.path.isdir(fullpath): if show_indexes: return directory_index(newpath, fullpath) raise Http404, "Directory indexes are not allowed here." # Respect the If-Modified-Since header. statobj = os.stat(fullpath) if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): return HttpResponseNotModified() mimetype = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream' contents = open(fullpath, 'rb').read() response = HttpResponse(mimetype=mimetype) response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) response["Content-Length"] = len(contents) # lighttpd only lighttpd_path = get_webserver_path(newpath) response['X-Sendfile'] = lighttpd_path new_filename = fullpath.split('/')[-1] new_filename = new_filename.replace(' ', '_') response['Content-Disposition'] = 'attachment;filename=%s' % new_filename return response
def h(*args, **kwargs): t = "%s/%s" % (kwargs['base'], kwargs['template']) if t.endswith('/'): template_path = os.path.join(settings.PROJECT_PATH, "templates", t) return directory_index(t.rstrip('/'), template_path) elif t.split('/')[-1].find('.') == -1: return redirect("/%s/" % t) kwargs['template'] = t return direct_to_template(*args, **kwargs)
def h(*args, **kwargs): t = "%s/%s" % (kwargs['base'], kwargs['template']) if t.endswith('/'): template_path = os.path.join(settings.PROJECT_PATH, "templates", t) return directory_index(t.rstrip('/'), template_path) elif t.split('/')[-1].find('.') == -1: return redirect("/%s/" % t) kwargs['template'] = t return direct_to_template(*args, **kwargs)
def media(request, path): fullpath = os.path.join(settings.STATIC_MEDIA_ROOT, path) mimetype = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream' # Rendering directory listing if os.path.isdir(fullpath): return directory_index(path, fullpath) # Render single file if not os.path.isdir('%s.d' % fullpath): try: modified = os.stat(fullpath)[stat.ST_MTIME] except OSError: raise Http404() if not was_modified_since( request.META.get('HTTP_IF_MODIFIED_SINCE'), modified, ): return HttpResponseNotModified(content_type=mimetype) contents = render_file(fullpath) response = HttpResponse(contents, content_type=mimetype) response['Last-Modified'] = http_date(modified) response['Content-Length'] = len(contents) return response # Render .d directory latest = -1 filenames = [] for root, _, files in os.walk('%s.d' % fullpath, followlinks=True): for filename in [os.path.join(root, x) for x in files]: if filename.endswith('~'): continue filenames.append(filename) latest = max(latest, os.stat(filename)[stat.ST_MTIME]) if not was_modified_since( request.META.get('HTTP_IF_MODIFIED_SINCE'), latest, ): return HttpResponseNotModified(content_type=mimetype) contents = "" for filename in sorted(filenames): contents += render_file(filename) response = HttpResponse(contents, content_type=mimetype) response['Last-Modified'] = http_date(latest) response['Content-Length'] = len(contents) return response
def media(request, path): fullpath = os.path.join(settings.STATIC_MEDIA_ROOT, path) mimetype = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream' # Rendering directory listing if os.path.isdir(fullpath): return directory_index(path, fullpath) # Render single file if not os.path.isdir('%s.d' % fullpath): try: modified = os.stat(fullpath)[stat.ST_MTIME] except OSError: raise Http404() if not was_modified_since( request.META.get('HTTP_IF_MODIFIED_SINCE'), modified, ): return HttpResponseNotModified(content_type=mimetype) contents = render_file(fullpath) response = HttpResponse(contents, content_type=mimetype) response['Last-Modified'] = http_date(modified) response['Content-Length'] = len(contents) return response # Render .d directory latest = -1 filenames = [] for root, _, files in os.walk('%s.d' % fullpath, followlinks=True): for filename in [os.path.join(root, x) for x in files]: if filename.endswith('~'): continue filenames.append(filename) latest = max(latest, os.stat(filename)[stat.ST_MTIME]) if not was_modified_since( request.META.get('HTTP_IF_MODIFIED_SINCE'), latest, ): return HttpResponseNotModified(content_type=mimetype) contents = "" for filename in sorted(filenames): contents += render_file(filename) response = HttpResponse(contents, content_type=mimetype) response['Last-Modified'] = http_date(latest) response['Content-Length'] = len(contents) return response
def serve(request, path, document_root=None, show_indexes=False, directory_index_allows=[]): path = posixpath.normpath(unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not part: # Strip empty path components. continue drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): # Strip '.' and '..' in path. continue newpath = os.path.join(newpath, part).replace('\\', '/') if newpath and path != newpath: return HttpResponseRedirect(newpath) fullpath = os.path.join(document_root, newpath) # ********** MODIFIED ************** if directory_index_allows: if os.path.isdir(fullpath): for index_filename in directory_index_allows: index_filepath = os.path.join(fullpath, index_filename) if os.path.isfile(index_filepath): fullpath = index_filepath break # ********************************** if os.path.isdir(fullpath): if show_indexes: return directory_index(newpath, fullpath) raise Http404(_("Directory indexes are not allowed here.")) if not os.path.exists(fullpath): raise Http404(_('"%(path)s" does not exist') % {'path': fullpath}) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj.st_mtime, statobj.st_size): return HttpResponseNotModified() content_type, encoding = mimetypes.guess_type(fullpath) content_type = content_type or 'application/octet-stream' response = FileResponse(open(fullpath, 'rb'), content_type=content_type) response["Last-Modified"] = http_date(statobj.st_mtime) if stat.S_ISREG(statobj.st_mode): response["Content-Length"] = statobj.st_size if encoding: response["Content-Encoding"] = encoding return response
def serve(request, path, document_root=None, show_indexes=False): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: (r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root' : '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(urllib.unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not part: # Strip empty path components. continue drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): # Strip '.' and '..' in path. continue newpath = os.path.join(newpath, part).replace('\\', '/') if newpath and path != newpath: return HttpResponseRedirect(newpath) fullpath = os.path.join(document_root, newpath) if os.path.isdir(fullpath): if show_indexes: return directory_index(newpath, fullpath) raise Http404("Directory indexes are not allowed here.") if not os.path.exists(fullpath): raise Http404('"%s" does not exist' % fullpath) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) mimetype, encoding = mimetypes.guess_type(fullpath) mimetype = mimetype or 'application/octet-stream' if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj.st_mtime, statobj.st_size): return HttpResponseNotModified(mimetype=mimetype) response = HttpResponse(open(fullpath, 'rb').read(), mimetype=mimetype) response["Last-Modified"] = http_date(statobj.st_mtime) response["Content-Length"] = statobj.st_size if encoding: response["Content-Encoding"] = encoding return response
def serve_static(request, path, document_root=None, show_indexes=False): path = posixpath.normpath(path).lstrip('/') fullpath = Path(safe_join(document_root, path)) if fullpath.is_dir(): if show_indexes: return directory_index(path, fullpath) raise Http404(_("Directory indexes are not allowed here.")) if not fullpath.exists(): raise Http404(_('“%(path)s” does not exist') % {'path': fullpath}) # Respect the If-Modified-Since header. statobj = fullpath.stat() if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj.st_mtime, statobj.st_size): return HttpResponseNotModified() content_type, encoding = mimetypes.guess_type(str(fullpath)) content_type = content_type or 'application/octet-stream' image = Image.open(fullpath) width, height = image.size try: req_width = int(request.GET.get('w')) except Exception: req_width = None try: req_height = int(request.GET.get('h')) except Exception: req_height = None if req_width is not None: req_height = int(req_width * height / width) elif req_height is not None: req_width = int(req_height * width / height) else: req_width = width req_height = height image = image.resize((req_width, req_height), Image.ANTIALIAS) output = io.BytesIO() image.save(output, format='JPEG') output.seek(0) response = FileResponse(output, content_type=content_type) response["Last-Modified"] = http_date(statobj.st_mtime) if encoding: response["Content-Encoding"] = encoding return response
def _serve_path(request, newpath, fullpath, show_indexes): if os.path.isdir(fullpath): if show_indexes: return directory_index(newpath, fullpath) raise Http404("Directory indexes are not allowed here.") if not os.path.exists(fullpath): raise Http404('"%s" does not exist' % fullpath) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): return HttpResponseNotModified() mimetype = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream' contents = open(fullpath, 'rb').read() response = HttpResponse(contents, mimetype=mimetype) response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) response["Content-Length"] = len(contents) return response
def html_design_view(*args, **kwargs): """ This will load design templates from the "html" directory in your templates folder. It's only turned on if DEBUG is True. It will also show indexes if you leave off the filename and extension. """ path = kwargs['path'] # The path is a directory if path.endswith('/'): directory = os.path.join(settings.HTML_DESIGN_ROOT, path) return directory_index(path.rstrip('/'), directory) # Missing a trailing slash elif '.' not in path.split('/')[-1].find('.'): return redirect('/%s/' % path) # Render the template kwargs['template'] = path return direct_to_template(*args, **kwargs)
def serve_protected_file(request, path, document_root=None, show_indexes=False): user_file = get_object_or_404(File, file=path) if user_file.user_id != request.user.id: raise Http404 path = posixpath.normpath(path).lstrip('/') fullpath = Path(safe_join(document_root, path)) if fullpath.is_dir(): if show_indexes: return directory_index(path, fullpath) raise Http404("Directory indexes are not allowed here.") if not fullpath.exists(): raise Http404('“%(path)s” does not exist' % {'path': fullpath}) # Respect the If-Modified-Since header. statobj = fullpath.stat() if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj.st_mtime, statobj.st_size): return HttpResponseNotModified() content_type, encoding = mimetypes.guess_type(str(fullpath)) content_type = content_type or 'application/octet-stream' response = FileResponse(fullpath.open('rb'), content_type=content_type) response["Last-Modified"] = http_date(statobj.st_mtime) if encoding: response["Content-Encoding"] = encoding return response
def serve_all(request, path, document_root=None): """ This view serves static media and directory indexes for a django application. It should only be used in development, media should be provided directly by a web server in production. This view assumes a django application stores its media in app/media (which is very common) and the file is referred to in the templates by the last part of a django app path. e.g. As in django.contrib.admin -> 'admin'. First we check if the media is a request in an application directory; if so we attempt to serve it from there. Then we attempt to provide the document from the document_root parameter (if provided). To use this view you should add something like the following to urls.py: if settings.DEBUG: urlpatterns += (r'^media/(?P<path>.*)$', 'site.media.serve_apps', {'document_root' : settings.MEDIA_ROOT}) You can then have the admin media files served by setting ADMIN_MEDIA_PREFIX = '/media/admin/' """ abspath = get_path(path, document_root) #find_abspath(path, document_root) or '' if not os.path.exists(abspath): raise Http404("No media found for path %s (tried '%s'), root: %s" % (path, abspath,document_root)) if os.path.isdir(abspath): # To make the template work a directory must have a trailing slash in the url # The one exception is when path == / if not path.endswith('/') and path: raise Http404("This path is a directory. Add a trailing slash to view index") return directory_index(path[:-1], abspath) mimetype = mimetypes.guess_type(abspath)[0] or 'application/octet-stream' contents = open(abspath, 'rb').read() response = HttpResponse(contents, mimetype=mimetype) response["Content-Length"] = len(contents) return response
def plugin_static_serve(request, plugin, path, show_indexes=False): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: (r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root' : '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ import mimetypes import os import posixpath import stat from six.moves.urllib.request import unquote from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseNotModified from django.utils.http import http_date from django.views.static import was_modified_since, directory_index from django.conf import settings document_root = os.path.join(settings.PROJECT_ROOT, 'plugins', plugin, 'media') # Clean up given path to only allow serving files below document_root. path = posixpath.normpath(unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not part: # Strip empty path components. continue drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): # Strip '.' and '..' in path. continue newpath = os.path.join(newpath, part).replace('\\', '/') if newpath and path != newpath: return HttpResponseRedirect(newpath) fullpath = os.path.join(document_root, newpath) if os.path.isdir(fullpath): if show_indexes: return directory_index(newpath, fullpath) raise Http404(_("Directory indexes are not allowed here.")) if not os.path.exists(fullpath): raise Http404('"%s" does not exist' % fullpath) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) mimetype = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream' if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): return HttpResponseNotModified(content_type=mimetype) contents = open(fullpath, 'rb').read() response = HttpResponse(contents, content_type=mimetype) response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) response["Content-Length"] = len(contents) return response
def directory(request): return directory_index("./", Path.cwd())
def plugin_static_serve(request, plugin, path, show_indexes=False): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: (r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root' : '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ import mimetypes import os import posixpath import stat import urllib from email.Utils import parsedate_tz, mktime_tz from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseNotModified from django.utils.http import http_date from django.views.static import was_modified_since, directory_index from django.conf import settings document_root = os.path.join(settings.PROJECT_ROOT,'plugins',plugin,'media') # Clean up given path to only allow serving files below document_root. path = posixpath.normpath(urllib.unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not part: # Strip empty path components. continue drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): # Strip '.' and '..' in path. continue newpath = os.path.join(newpath, part).replace('\\', '/') if newpath and path != newpath: return HttpResponseRedirect(newpath) fullpath = os.path.join(document_root, newpath) if os.path.isdir(fullpath): if show_indexes: return directory_index(newpath, fullpath) raise Http404("Directory indexes are not allowed here.") if not os.path.exists(fullpath): raise Http404('"%s" does not exist' % fullpath) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) mimetype = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream' if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): return HttpResponseNotModified(mimetype=mimetype) contents = open(fullpath, 'rb').read() response = HttpResponse(contents, mimetype=mimetype) response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) response["Content-Length"] = len(contents) return response