Python django.views.static.serve() Examples

The following are 30 code examples of django.views.static.serve(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.views.static , or try the search function .
Example #1
Source File: servers.py    From django-private-storage with Apache License 2.0 10 votes vote down vote up
def serve(private_file):
        # Support If-Last-Modified
        if sys.version_info >= (3,):
            mtime = private_file.modified_time.timestamp()
        else:
            mtime = time.mktime(private_file.modified_time.timetuple())
        size = private_file.size
        if not was_modified_since(private_file.request.META.get('HTTP_IF_MODIFIED_SINCE'), mtime, size):
            return HttpResponseNotModified()

        # As of Django 1.8, FileResponse triggers 'wsgi.file_wrapper' in Django's WSGIHandler.
        # This uses efficient file streaming, such as sendfile() in uWSGI.
        # When the WSGI container doesn't provide 'wsgi.file_wrapper', it submits the file in 4KB chunks.
        if private_file.request.method == 'HEAD':
            # Avoid reading the file at all
            response = HttpResponse()
        else:
            response = FileResponse(private_file.open())
        response['Content-Type'] = private_file.content_type
        response['Content-Length'] = size
        response["Last-Modified"] = http_date(mtime)
        return response 
Example #2
Source File: views.py    From pinax-documents with MIT License 8 votes vote down vote up
def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        if settings.DOCUMENTS_USE_X_ACCEL_REDIRECT:
            response = HttpResponse()
            response["X-Accel-Redirect"] = self.object.file.url
            # delete content-type to allow Gondor to determine the filetype and
            # we definitely don't want Django's crappy default :-)
            del response["content-type"]
        else:
            # Note:
            #
            # The 'django.views.static.py' docstring states:
            #
            #     Views and functions for serving static files. These are only to be used
            #     during development, and SHOULD NOT be used in a production setting.
            #
            response = static.serve(request, self.object.file.name,
                                    document_root=settings.MEDIA_ROOT)
        return response 
Example #3
Source File: servers.py    From django-private-storage with Apache License 2.0 7 votes vote down vote up
def serve(private_file):
        # This supports If-Modified-Since and sends the file in 4KB chunks
        try:
            full_path = private_file.full_path
        except NotImplementedError:
            # S3 files, fall back to streaming server
            return DjangoStreamingServer.serve(private_file)
        else:
            # Using Django's serve gives If-Modified-Since support out of the box.
            response = serve(private_file.request, full_path, document_root='/', show_indexes=False)
            if private_file.request.method == 'HEAD' and response.status_code == 200:
                # Avoid reading the file at all, copy FileResponse headers
                # This is not needed for HttpResponseNotModified(), hence the 200 code check
                head_response = HttpResponse(status=response.status_code)
                for header, value in response.items():
                    head_response[header] = value
                return head_response
            else:
                return response 
Example #4
Source File: views.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def serve(request, path, insecure=False, **kwargs):
    """
    Serve static files below a given point in the directory structure or
    from locations inferred from the staticfiles finders.

    To use, put a URL pattern such as::

        from django.contrib.staticfiles import views

        url(r'^(?P<path>.*)$', views.serve)

    in your URLconf.

    It uses the django.views.static.serve() view to serve the found files.
    """
    if not settings.DEBUG and not insecure:
        raise Http404
    normalized_path = posixpath.normpath(unquote(path)).lstrip('/')
    absolute_path = finders.find(normalized_path)
    if not absolute_path:
        if path.endswith('/') or path == '':
            raise Http404("Directory indexes are not allowed here.")
        raise Http404("'%s' could not be found" % path)
    document_root, path = os.path.split(absolute_path)
    return static.serve(request, path, document_root=document_root, **kwargs) 
Example #5
Source File: views.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def serve(request, path, insecure=False, **kwargs):
    """
    Serve static files below a given point in the directory structure or
    from locations inferred from the staticfiles finders.

    To use, put a URL pattern such as::

        from django.contrib.staticfiles import views

        url(r'^(?P<path>.*)$', views.serve)

    in your URLconf.

    It uses the django.views.static.serve() view to serve the found files.
    """
    if not settings.DEBUG and not insecure:
        raise Http404
    normalized_path = posixpath.normpath(path).lstrip('/')
    absolute_path = finders.find(normalized_path)
    if not absolute_path:
        if path.endswith('/') or path == '':
            raise Http404("Directory indexes are not allowed here.")
        raise Http404("'%s' could not be found" % path)
    document_root, path = os.path.split(absolute_path)
    return static.serve(request, path, document_root=document_root, **kwargs) 
Example #6
Source File: views.py    From python2017 with MIT License 6 votes vote down vote up
def serve(request, path, insecure=False, **kwargs):
    """
    Serve static files below a given point in the directory structure or
    from locations inferred from the staticfiles finders.

    To use, put a URL pattern such as::

        from django.contrib.staticfiles import views

        url(r'^(?P<path>.*)$', views.serve)

    in your URLconf.

    It uses the django.views.static.serve() view to serve the found files.
    """
    if not settings.DEBUG and not insecure:
        raise Http404
    normalized_path = posixpath.normpath(unquote(path)).lstrip('/')
    absolute_path = finders.find(normalized_path)
    if not absolute_path:
        if path.endswith('/') or path == '':
            raise Http404("Directory indexes are not allowed here.")
        raise Http404("'%s' could not be found" % path)
    document_root, path = os.path.split(absolute_path)
    return static.serve(request, path, document_root=document_root, **kwargs) 
Example #7
Source File: views.py    From bioforum with MIT License 6 votes vote down vote up
def serve(request, path, insecure=False, **kwargs):
    """
    Serve static files below a given point in the directory structure or
    from locations inferred from the staticfiles finders.

    To use, put a URL pattern such as::

        from django.contrib.staticfiles import views

        url(r'^(?P<path>.*)$', views.serve)

    in your URLconf.

    It uses the django.views.static.serve() view to serve the found files.
    """
    if not settings.DEBUG and not insecure:
        raise Http404
    normalized_path = posixpath.normpath(path).lstrip('/')
    absolute_path = finders.find(normalized_path)
    if not absolute_path:
        if path.endswith('/') or path == '':
            raise Http404("Directory indexes are not allowed here.")
        raise Http404("'%s' could not be found" % path)
    document_root, path = os.path.split(absolute_path)
    return static.serve(request, path, document_root=document_root, **kwargs) 
Example #8
Source File: views.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def serve(request, path, insecure=False, **kwargs):
    """
    Serve static files below a given point in the directory structure or
    from locations inferred from the staticfiles finders.

    To use, put a URL pattern such as::

        from django.contrib.staticfiles import views

        url(r'^(?P<path>.*)$', views.serve)

    in your URLconf.

    It uses the django.views.static.serve() view to serve the found files.
    """
    if not settings.DEBUG and not insecure:
        raise Http404
    normalized_path = posixpath.normpath(unquote(path)).lstrip('/')
    absolute_path = finders.find(normalized_path)
    if not absolute_path:
        if path.endswith('/') or path == '':
            raise Http404("Directory indexes are not allowed here.")
        raise Http404("'%s' could not be found" % path)
    document_root, path = os.path.split(absolute_path)
    return static.serve(request, path, document_root=document_root, **kwargs) 
Example #9
Source File: testcases.py    From python with Apache License 2.0 5 votes vote down vote up
def serve(self, request):
        os_rel_path = self.file_path(request.path)
        os_rel_path = posixpath.normpath(unquote(os_rel_path))
        # Emulate behavior of django.contrib.staticfiles.views.serve() when it
        # invokes staticfiles' finders functionality.
        # TODO: Modify if/when that internal API is refactored
        final_rel_path = os_rel_path.replace('\\', '/').lstrip('/')
        return serve(request, final_rel_path, document_root=self.get_base_dir()) 
Example #10
Source File: views.py    From SOMS with GNU General Public License v3.0 5 votes vote down vote up
def protected_serve(request, path, document_root=None):
    temp = path.split('/')
    if request.user.pk == int(temp[1]):
        return serve(request, path, document_root)
    else:
        # return HttpResponse("无权限查看!")
        raise Http404 
Example #11
Source File: views.py    From feedthefox with Mozilla Public License 2.0 5 votes vote down vote up
def contribute_view(request):
    """Serve a contribute.json file."""
    return serve(request, 'contribute.json', document_root=settings.BASE_DIR) 
Example #12
Source File: testcases.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def serve(self, request):
        relative_url = request.path[len(self.base_url[2]):]
        return serve(request, relative_url, document_root=self.get_base_dir()) 
Example #13
Source File: urls.py    From baobab with GNU General Public License v3.0 5 votes vote down vote up
def baobab_serve(request, path, document_root=None, show_indexes=False):
    if not settings.INFINITE_CACHE:
        return serve(request, path, document_root, show_indexes)
    else:
        if _serve_gzip(request):
            resp = serve(request, path + '.gz', document_root, show_indexes)
            resp['Content-Encoding'] = 'gzip'
        else:
            resp = serve(request, path, document_root, show_indexes)
        resp['Cache-Control'] = 'public, max-age=%d' % (3600 * 24 * 365)
        resp['Vary'] = 'Accept-Encoding'
        return resp

# back-end URL 
Example #14
Source File: testcases.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_response(self, request):
        from django.http import Http404

        if self._should_handle(request.path):
            try:
                return self.serve(request)
            except Http404:
                pass
        return super(FSFilesHandler, self).get_response(request) 
Example #15
Source File: testcases.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def serve(self, request):
        os_rel_path = self.file_path(request.path)
        os_rel_path = posixpath.normpath(unquote(os_rel_path))
        # Emulate behavior of django.contrib.staticfiles.views.serve() when it
        # invokes staticfiles' finders functionality.
        # TODO: Modify if/when that internal API is refactored
        final_rel_path = os_rel_path.replace('\\', '/').lstrip('/')
        return serve(request, final_rel_path, document_root=self.get_base_dir()) 
Example #16
Source File: static.py    From python2017 with MIT License 5 votes vote down vote up
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::

        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()
    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 
Example #17
Source File: views.py    From pinax-wiki with MIT License 5 votes vote down vote up
def file_download(request, pk, filename):
    media_file = get_object_or_404(MediaFile, pk=pk, filename=filename)
    if getattr(settings, "DOCUMENTS_USE_X_ACCEL_REDIRECT", False):
        response = HttpResponse()
        response["X-Accel-Redirect"] = media_file.file.url
        # delete content-type to allow Gondor to determine the filetype and
        # we definitely don't want Django's crappy default :-)
        del response["content-type"]
    else:
        response = static.serve(request, media_file.file.name, document_root=settings.MEDIA_ROOT)
    return response 
Example #18
Source File: testcases.py    From python2017 with MIT License 5 votes vote down vote up
def get_response(self, request):
        from django.http import Http404

        if self._should_handle(request.path):
            try:
                return self.serve(request)
            except Http404:
                pass
        return super(FSFilesHandler, self).get_response(request) 
Example #19
Source File: testcases.py    From python2017 with MIT License 5 votes vote down vote up
def serve(self, request):
        os_rel_path = self.file_path(request.path)
        os_rel_path = posixpath.normpath(unquote(os_rel_path))
        # Emulate behavior of django.contrib.staticfiles.views.serve() when it
        # invokes staticfiles' finders functionality.
        # TODO: Modify if/when that internal API is refactored
        final_rel_path = os_rel_path.replace('\\', '/').lstrip('/')
        return serve(request, final_rel_path, document_root=self.get_base_dir()) 
Example #20
Source File: views.py    From iguana with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def get(self, request, content_disposition_type="inline", *args, **kwargs):
        if USE_X_ACCEL_REDIRECT:
            response = HttpResponse('')
            if X_ACCEL_REDIRECT_PREFIX is not None:
                first_path_element = re.compile("^/([^/]*)/").search(request.path).group(1)
                request.path = request.path.replace(first_path_element, X_ACCEL_REDIRECT_PREFIX, 1)
            response['X-Accel-Redirect'] = request.path
            response['Content-Type'] = ''

        else:
            response = serve(request, request.path, settings.FILES_DIR)

        return response 
Example #21
Source File: urls.py    From texta with GNU General Public License v3.0 5 votes vote down vote up
def protected_serve(request, path, document_root=None, show_indexes=False):
    return serve(request, path, document_root, show_indexes) 
Example #22
Source File: development.py    From django-sendfile2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sendfile(request, filename, **kwargs):
    """
    Send file using Django dev static file server.

    .. warning::

        Do not use in production. This is only to be used when developing and
        is provided for convenience only
    """
    dirname = os.path.dirname(filename)
    basename = os.path.basename(filename)
    return serve(request, basename, dirname) 
Example #23
Source File: static.py    From python with Apache License 2.0 5 votes vote down vote up
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::

        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()
    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 
Example #24
Source File: testcases.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_response(self, request):
        from django.http import Http404

        if self._should_handle(request.path):
            try:
                return self.serve(request)
            except Http404:
                pass
        return super(FSFilesHandler, self).get_response(request) 
Example #25
Source File: testcases.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def serve(self, request):
        os_rel_path = self.file_path(request.path)
        os_rel_path = posixpath.normpath(unquote(os_rel_path))
        # Emulate behavior of django.contrib.staticfiles.views.serve() when it
        # invokes staticfiles' finders functionality.
        # TODO: Modify if/when that internal API is refactored
        final_rel_path = os_rel_path.replace('\\', '/').lstrip('/')
        return serve(request, final_rel_path, document_root=self.get_base_dir()) 
Example #26
Source File: static.py    From bioforum with MIT License 5 votes vote down vote up
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::

        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(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()
    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 
Example #27
Source File: testcases.py    From bioforum with MIT License 5 votes vote down vote up
def get_response(self, request):
        from django.http import Http404

        if self._should_handle(request.path):
            try:
                return self.serve(request)
            except Http404:
                pass
        return super().get_response(request) 
Example #28
Source File: testcases.py    From bioforum with MIT License 5 votes vote down vote up
def serve(self, request):
        os_rel_path = self.file_path(request.path)
        os_rel_path = posixpath.normpath(unquote(os_rel_path))
        # Emulate behavior of django.contrib.staticfiles.views.serve() when it
        # invokes staticfiles' finders functionality.
        # TODO: Modify if/when that internal API is refactored
        final_rel_path = os_rel_path.replace('\\', '/').lstrip('/')
        return serve(request, final_rel_path, document_root=self.get_base_dir()) 
Example #29
Source File: servers.py    From django-private-storage with Apache License 2.0 5 votes vote down vote up
def serve(private_file):
        response = HttpResponse()
        response['X-Sendfile'] = private_file.full_path
        response['Content-Type'] = private_file.content_type
        return response 
Example #30
Source File: servers.py    From django-private-storage with Apache License 2.0 5 votes vote down vote up
def serve(private_file):
        internal_url = os.path.join(settings.PRIVATE_STORAGE_INTERNAL_URL, private_file.relative_name)
        if NginxXAccelRedirectServer.should_quote():
            internal_url = quote(internal_url)
        response = HttpResponse()
        response['X-Accel-Redirect'] = internal_url
        response['Content-Type'] = private_file.content_type
        return response