示例#1
0
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
示例#2
0
文件: views.py 项目: lamby/31bananas
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
示例#3
0
def was_modified_since (request, path) :
	statobj = os.stat(path)
	return django_static.was_modified_since(
		request.META.get("HTTP_IF_MODIFIED_SINCE", None),
		statobj[stat.ST_MTIME],
		statobj[stat.ST_SIZE]
	)
示例#4
0
def sendfile(request, filename):
    # Respect the If-Modified-Since header.
    if not os.path.isfile(filename):
        raise Http404
    statobj = os.stat(filename)
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
        return HttpResponseNotModified()
    content_type = mimetypes.guess_type(filename)[0]
    range_ = request.META.get('HTTP_RANGE', '')
    t = range_re.match(range_)
    size = os.path.getsize(filename)
    start = 0
    end = size - 1
    if t:
        start, end = int(t.group(1)), int(t.group(2))
    if end - start + 1 < size:
        obj = open(filename, 'rb')
        obj.seek(start)
        response = HttpResponse(obj.read(end - start + 1), content_type=content_type, status=206)
        response['Content-Range'] = 'bytes %d-%d/%d' % (start, end, size)
    else:
        obj = open(filename, 'rb')
        return StreamingHttpResponse(obj, content_type=content_type)
    response['Content-Length'] = end - start + 1
    #response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
    return response
示例#5
0
def serve_private_media(request, path):
    """Serve a private media file with the webserver's "sendfile" if possible.

    Here's an example of how to use this function. The 'Document' model tracks
    files. It provides a 'get_file_path' method returning the absolute path to
    the actual file. The following view serves file only to users having the
    'can_download' permission::

        @permission_required('documents.can_download')
        def download_document(request, document_id):
            path = Document.objects.get(pk=document_id).get_file_path()
            return serve_private_media(request, path)

    If ``DEBUG`` is ``False`` and ``settings.GALLERY_SENDFILE_HEADER`` is set,
    this function sets a header and doesn't send the actual contents of the
    file. Use ``'X-Accel-Redirect'`` for nginx and ``'X-SendFile'`` for Apache
    with mod_xsendfile. Otherwise, this function behaves like Django's static
    serve view.

    ``path`` must be an absolute path. Depending on your webserver's
    configuration, you might want a full path or a relative path in the
    header's value. ``settings.GALLERY_SENDFILE_ROOT`` will be stripped from
    the beginning of the path to create the header's value.
    """

    if not os.path.exists(path):
        # Don't reveal the file name on the filesystem.
        raise Http404("Requested file doesn't exist.")

    # begin copy-paste from django.views.static.serve
    statobj = os.stat(path)
    content_type, encoding = mimetypes.guess_type(path)
    content_type = content_type or 'application/octet-stream'
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj.st_mtime, statobj.st_size):   # pragma: no cover
        return HttpResponseNotModified()
    # pause copy-paste from django.views.static.serve

    sendfile_header = getattr(settings, 'GALLERY_SENDFILE_HEADER', '')
    sendfile_root = getattr(settings, 'GALLERY_SENDFILE_ROOT', '')

    if settings.DEBUG or not sendfile_header:
        response = StreamingHttpResponse(open(path, 'rb'), content_type=content_type)
    else:
        response = HttpResponse('', content_type=content_type)
        if sendfile_root:
            if not path.startswith(sendfile_root):
                raise ValueError("Requested file isn't under GALLERY_SENDFILE_ROOT.")
            path = path[len(sendfile_root):]
        response[sendfile_header] = path.encode(sys.getfilesystemencoding())

    # resume copy-paste from django.views.static.serve
    response["Last-Modified"] = http_date(statobj.st_mtime)
    if stat.S_ISREG(statobj.st_mode):                       # pragma: no cover
        response["Content-Length"] = statobj.st_size
    if encoding:                                            # pragma: no cover
        response["Content-Encoding"] = encoding
    # end copy-paste from django.views.static.serve

    return response
def get_media_internal (request, path, use_cache=True) :
	statobj = os.stat(path)
	(st_mtime, st_size, ) = (statobj[stat.ST_MTIME], statobj[stat.ST_SIZE], )

	if not django_static.was_modified_since(
			request.META.get("HTTP_IF_MODIFIED_SINCE", None), st_mtime, st_size) :
		status_code = 304
		mimetype = None
		contents = None
	else :
		status_code = 200

		if use_cache :
			__argument = request.GET.copy()

			# We use cache. If you did not enable the caching, nothing will be happended.
			__path_cache = urllib.quote("%s?%s" % (path, __argument.urlencode()), "")
			__response = cache.get(__path_cache)
			if __response :
				return (None, None, status_code, None, __response, )

		# get media type
		mimetype = mimetypes.guess_type(path)[0]

		__media_type = "func_%s" % mimetype.replace("/", "_").replace("-", "__")
		if globals().has_key(__media_type) :
			fn = globals().get(__media_type)
		else :
			__media_type = mimetype.split("/")[0]
			fn = globals().get("func_%s" % __media_type, func_default)

		contents = fn(request, path)

	return (contents, mimetype, status_code, rfc822.formatdate(st_mtime), None, )
示例#7
0
    def render_to_response(self, **response_kwargs):
        '''
        Use class data to make a Django HTTP response.
        Would only in most universes be implemented on 'get'
        '''
        #NB some code here comes from django.views.static
        fullpath = self.get_fullpath()

        # Respect the If-Modified-Since header.
        statobj = fullpath.stat()
        if not was_modified_since(
                self.request.META.get('HTTP_IF_MODIFIED_SINCE'),
                statobj.st_mtime, statobj.st_size):
            return HttpResponseNotModified()
        try:
            f = fullpath.open('rb')
        except FileNotFoundError:
            raise Http404(_('“%(path)s” does not exist') % {'path': fullpath})

        response = AssuredFileResponse(f,
                                       as_attachment=False,
                                       content_type='text/html',
                                       **response_kwargs)
        response["Last-Modified"] = http_date(statobj.st_mtime)
        return response
示例#8
0
    def was_modified_since(self, file_instance, since):
        """Return True if ``file_instance`` was modified after ``since``.

        Uses file wrapper's ``was_modified_since`` if available, with value of
        ``since`` as positional argument.

        Else, fallbacks to default implementation, which uses
        :py:func:`django.views.static.was_modified_since`.

        Django's ``was_modified_since`` function needs a datetime and a size.
        It is passed ``modified_time`` and ``size`` attributes from file
        wrapper. If file wrapper does not support these attributes
        (``AttributeError`` or ``NotImplementedError`` is raised), then
        the file is considered as modified and ``True`` is returned.

        """
        try:
            return file_instance.was_modified_since(since)
        except (AttributeError, NotImplementedError):
            try:
                modification_time = calendar.timegm(
                    file_instance.modified_time.utctimetuple())
                size = file_instance.size
            except (AttributeError, NotImplementedError) as e:
                print("!=======!", e)
                return True
            else:
                return was_modified_since(since, modification_time, size)
示例#9
0
def served(request, absolute_path):
    latest = -1
    filenames = []

    for root, _, files in os.walk('%s.d' % absolute_path, 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])

    mimetype = mimetypes.guess_type(absolute_path)[0] or 'application/octet-stream'

    if not was_modified_since(
        request.META.get('HTTP_IF_MODIFIED_SINCE'),
        latest,
    ):
        return HttpResponseNotModified(content_type=mimetype)

    fn = get_dotted_path(app_settings.RENDER_FN)
    contents = ''.join(fn(x) for x in sorted(filenames))

    # Ensure bytes otherwise our len(contents) can be short!
    contents = force_bytes(contents)

    response = HttpResponse(contents, content_type=mimetype)
    response['Last-Modified'] = http_date(latest)
    response['Content-Length'] = len(contents)

    return response
示例#10
0
 def test_was_modified_since_fp(self):
     """
     A floating point mtime does not disturb was_modified_since (#18675).
     """
     mtime = 1343416141.107817
     header = http_date(mtime)
     self.assertFalse(was_modified_since(header, mtime))
def get_media_internal (request, path) :
	statobj = os.stat(path)
	(st_mtime, st_size, ) = (statobj[stat.ST_MTIME], statobj[stat.ST_SIZE], )

	if not django_static.was_modified_since(
			request.META.get("HTTP_IF_MODIFIED_SINCE", None), st_mtime, st_size) :
		status_code = 304
		mimetype = None
		contents = None
	else :
		status_code = 200

		# get media type
		mimetype = mimetypes.guess_type(path)[0]

		__media_type = "func_%s" % mimetype.replace("/", "_").replace("-", "__")
		if globals().has_key(__media_type) :
			fn = globals().get(__media_type)
		else :
			__media_type = mimetype.split("/")[0]
			fn = globals().get("func_%s" % __media_type, func_default)

		contents = fn(request, path)

	return (contents, mimetype, status_code, rfc822.formatdate(st_mtime), )
示例#12
0
    def render_thumbnail(self, thumbnail, factor):
        """
        Generate the http response for the requested thumbnail.
        The code is able response with 304 if the thumbnail was already requested.

        Supports X-Accel-Redirect, enabled by default if DEBUG is False.
        """
        path = thumbnail.get_storage_path(factor)

        thumbnail_stat = os.stat(path)
        mimetype = thumbnail.get_mimetype()

        # Check for last modified.
        if not was_modified_since(
                self.request.META.get('HTTP_IF_MODIFIED_SINCE'),
                thumbnail_stat.st_mtime,
                thumbnail_stat.st_size,
        ):
            return HttpResponseNotModified()

        if getattr(settings, 'ULTIMATETHUMB_USE_X_ACCEL_REDIRECT',
                   not settings.DEBUG):
            response = HttpResponse(content_type=mimetype)
            response['X-Accel-Redirect'] = urlparse(
                thumbnail.get_storage_url(factor)).path
        else:
            with open(path, 'rb') as file:
                response = HttpResponse(file.read(), content_type=mimetype)

        # Respect the If-Modified-Since header.
        response['Last-Modified'] = http_date(thumbnail_stat.st_mtime)
        response['Content-Length'] = thumbnail_stat.st_size

        return response
示例#13
0
 def test_was_modified_since_fp(self):
     """
     A floating point mtime does not disturb was_modified_since (#18675).
     """
     mtime = 1343416141.107817
     header = http_date(mtime)
     self.assertFalse(was_modified_since(header, mtime))
示例#14
0
def serve_image(request, basename, encoded_spec, ext):
    try:
        image = Image(url=basename)
    except OSError:
        raise Http404()

    try:
        spec = Spec.from_spec(
            decode_spec(encoded_spec, image.basename, image.mtime,
                        settings.SIMPLETHUMB_HMAC_KEY))
    except ChecksumException:
        raise Http404()

    image.spec = spec

    mimetype = mimetypes.guess_type(request.path)[0]
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              image.mtime, image.stat.st_size):
        return HttpResponseNotModified(content_type=mimetype)

    expire_time = settings.SIMPLETHUMB_EXPIRE_HEADER

    resp = HttpResponse(image.render(), mimetype)
    resp['Expires'] = http_date(time.time() + expire_time)
    resp['Last-Modified'] = http_date(image.mtime)

    return resp
示例#15
0
def was_modified_since (request, path) :
	statobj = os.stat(path)
	return django_static.was_modified_since(
		request.META.get("HTTP_IF_MODIFIED_SINCE", None),
		statobj[stat.ST_MTIME],
		statobj[stat.ST_SIZE]
	)
示例#16
0
    def was_modified_since(self, file_instance, since):
        """Return True if ``file_instance`` was modified after ``since``.

        Uses file wrapper's ``was_modified_since`` if available, with value of
        ``since`` as positional argument.

        Else, fallbacks to default implementation, which uses
        :py:func:`django.views.static.was_modified_since`.

        Django's ``was_modified_since`` function needs a datetime and a size.
        It is passed ``modified_time`` and ``size`` attributes from file
        wrapper. If file wrapper does not support these attributes
        (``AttributeError`` or ``NotImplementedError`` is raised), then
        the file is considered as modified and ``True`` is returned.

        """
        try:
            return file_instance.was_modified_since(since)
        except (AttributeError, NotImplementedError):
            try:
                modification_time = calendar.timegm(
                    file_instance.modified_time.utctimetuple())
                size = file_instance.size
            except (AttributeError, NotImplementedError):
                return True
            else:
                return was_modified_since(since, modification_time, size)
示例#17
0
文件: files.py 项目: nirgal/ngw
    def get(self, request, fid, cid):
        cf = get_object_or_404(ContactField, pk=fid)
        if not perms.c_can_view_fields_cg(request.user.id,
                                          cf.contact_group_id):
            raise PermissionDenied
        fullpath = os.path.join(settings.MEDIA_ROOT, 'fields', fid, cid)
        if not os.path.exists(fullpath):
            raise Http404(_('"{path}" does not exist').format(path=fullpath))
        # Respect the If-Modified-Since header.
        statobj = os.stat(fullpath)
        if not static.was_modified_since(
           request.META.get('HTTP_IF_MODIFIED_SINCE'),
           statobj.st_mtime, statobj.st_size):
            return HttpResponseNotModified()

        # START OF content_type detection
        cfv = get_object_or_404(ContactFieldValue,
                                contact_id=cid, contact_field_id=fid)
        fileinfo = json.loads(cfv.value)
        content_type = fileinfo['content_type']
        # END OF content_type detection

        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

        response['Content-Disposition'] = 'inline; filename="{0}"'.format(
            header_encode(fileinfo['filename'].encode('utf-8'), 'utf-8'))
        return response
示例#18
0
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
示例#19
0
    def render_thumbnail(self, thumbnail, factor):
        path = thumbnail.get_storage_path(factor)

        thumbnail_stat = os.stat(path)
        mimetype, encoding = guess_type(path)

        # No mimetype detected, set default.
        mimetype = mimetype or "application/octet-stream"

        # Check for last modified.
        if not was_modified_since(
            self.request.META.get("HTTP_IF_MODIFIED_SINCE"), thumbnail_stat.st_mtime, thumbnail_stat.st_size
        ):
            return HttpResponseNotModified()

        if getattr(settings, "ULTIMATETHUMB_USE_X_ACCEL_REDIRECT", not settings.DEBUG):
            response = HttpResponse(content_type=mimetype)
            response["X-Accel-Redirect"] = urlparse(thumbnail.get_storage_url(factor)).path
        else:
            with open(path, "rb") as file:
                response = HttpResponse(file.read(), content_type=mimetype)

        # Respect the If-Modified-Since header.
        response["Last-Modified"] = http_date(thumbnail_stat.st_mtime)
        response["Content-Length"] = thumbnail_stat.st_size

        return response
示例#20
0
def static_serve(request, path):
    """
    Given a request for a media asset, this view does the necessary wrangling
    to get the correct thing delivered to the user. This can also emulate the
    combo behavior seen when SERVE_REMOTE == False and EMULATE_COMBO == True.
    """
    # Django static serve view.
    #dr = os.path.join(settings.ROOT_PATH, '../static/')
    mimetype, encoding = mimetypes.guess_type(path)
    mimetype = mimetype or 'application/octet-stream'
    env.process()

    outputs = env.outputs()
    resource = outputs[path]
    last_modified = resource.last_modified
    size = len(resource.content)
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              last_modified, size):
        return HttpResponseNotModified(mimetype=mimetype)

    response = HttpResponse(resource.content, mimetype=mimetype)
    response["Last-Modified"] = http_date(last_modified)
    response["Content-Length"] = size

    #resp = serve(request, path, document_root=dr, show_indexes=True)
    #resp.content = client.process(resp.content, resp['Content-Type'], path)
    return response
示例#21
0
def serve_folder_view(request, *args, **kwargs):
    file_name = kwargs.get('file_name')
    if not file_name:
        file_name = 'index.html'
    folders = getattr(settings, 'FOLDERVIEW_FOLDERS', None)
    if not folders:
        raise Http404("No folderview folders found")
    for folder in folders:
        fullpath = os.path.join(folder, file_name)
        if os.path.isfile(fullpath):
            break
    else:
        raise Http404("File {} not found in folderview".format(file_name))
    # Respect the If-Modified-Since header.
    statobj = os.stat(fullpath)
    if not static.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
示例#22
0
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
示例#23
0
文件: views.py 项目: ixiaoshayu/hue
def download(request, path):
    """
    Downloads a file.

    This is inspired by django.views.static.serve.
    ?disposition={attachment, inline}
    """
    if not request.fs.exists(path):
        raise Http404(_("File not found: %(path)s.") % {'path': escape(path)})
    if not request.fs.isfile(path):
        raise PopupException(_("'%(path)s' is not a file.") % {'path': path})

    mimetype = mimetypes.guess_type(path)[0] or 'application/octet-stream'
    stats = request.fs.stats(path)
    mtime = stats['mtime']
    size = stats['size']
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), mtime, size):
        return HttpResponseNotModified()
        # TODO(philip): Ideally a with statement would protect from leaks,
    # but tricky to do here.
    fh = request.fs.open(path)

    response = HttpResponse(_file_reader(fh), mimetype=mimetype)
    response["Last-Modified"] = http_date(stats['mtime'])
    response["Content-Length"] = stats['size']
    response['Content-Disposition'] = request.GET.get('disposition', 'attachment')
    return response
示例#24
0
def serve_private_media(request, path):
    """Serve a private media file with the webserver's "sendfile" if possible.

    Here's an example of how to use this function. The 'Document' model tracks
    files. It provides a 'get_file_path' method returning the absolute path to
    the actual file. The following view serves file only to users having the
    'can_download' permission::

        @permission_required('documents.can_download')
        def download_document(request, document_id):
            path = Document.objects.get(pk=document_id).get_file_path()
            return serve_private_media(request, path)

    If ``DEBUG`` is ``False`` and ``settings.GALLERY_SENDFILE_HEADER`` is set,
    this function sets a header and doesn't send the actual contents of the
    file. Use ``'X-Accel-Redirect'`` for nginx and ``'X-SendFile'`` for Apache
    with mod_xsendfile. Otherwise, this function behaves like Django's static
    serve view.

    ``path`` must be an absolute path. Depending on your webserver's
    configuration, you might want a full path or a relative path in the
    header's value. ``settings.GALLERY_SENDFILE_ROOT`` will be stripped from
    the beginning of the path to create the header's value.
    """

    if not os.path.exists(path):
        # Don't reveal the file name on the filesystem.
        raise Http404("Requested file doesn't exist.")

    # begin copy-paste from django.views.static.serve
    statobj = os.stat(path)
    content_type, encoding = mimetypes.guess_type(path)
    content_type = content_type or 'application/octet-stream'
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj.st_mtime, statobj.st_size):   # pragma: no cover
        return HttpResponseNotModified()
    # pause copy-paste from django.views.static.serve

    sendfile_header = getattr(settings, 'GALLERY_SENDFILE_HEADER', '')
    sendfile_root = getattr(settings, 'GALLERY_SENDFILE_ROOT', '')

    if settings.DEBUG or not sendfile_header:
        response = StreamingHttpResponse(open(path, 'rb'), content_type=content_type)
    else:
        response = HttpResponse('', content_type=content_type)
        if sendfile_root:
            if not path.startswith(sendfile_root):
                raise ValueError("Requested file isn't under GALLERY_SENDFILE_ROOT.")
            path = path[len(sendfile_root):]
        response[sendfile_header] = path.encode(sys.getfilesystemencoding())

    # resume copy-paste from django.views.static.serve
    response["Last-Modified"] = http_date(statobj.st_mtime)
    if stat.S_ISREG(statobj.st_mode):                       # pragma: no cover
        response["Content-Length"] = statobj.st_size
    if encoding:                                            # pragma: no cover
        response["Content-Encoding"] = encoding
    # end copy-paste from django.views.static.serve

    return response
示例#25
0
    def get(self, request, md5):
        user_id = request.session.get('user_id')
        if not user_id:
            raise Http404
        file = File.objects.filter(md5=md5, user_id=user_id).first()

        if not file:
            raise Http404
        statobj = os.stat(file.addr)
        if not was_modified_since(
                request.META.get('HTTP_IF_MODIFIED_SINCE'),
                statobj.st_mtime, statobj.st_size
        ):
            return HttpResponseNotModified()

        # 文件起点位置
        start_bytes = re.search(r'bytes=(\d+)-', request.META.get('HTTP_RANGE', ''), re.S)
        start_bytes = int(start_bytes.group(1)) if start_bytes else 0

        # 移动文件至上次下载位置
        the_file = open(file.addr, 'rb')
        the_file.seek(start_bytes, os.SEEK_SET)

        '''
        status=200表示下载开始,status=206表示下载暂停后继续,为了兼容火狐浏览器而区分两种状态
        关于django的response对象,参考:https://www.cnblogs.com/scolia/p/5635546.html
        关于response的状态码,参考:https://www.cnblogs.com/DeasonGuan/articles/Hanami.html
        FileResponse默认block_size = 4096,因此迭代器每次读取4KB数据
        '''
        response = FileResponse(
            the_file,
            content_type=file.mimetype or 'application/octet-stream',
            status=206 if start_bytes > 0 else 200)

        # 文件修改时间
        response['Last-Modified'] = http_date(statobj.st_mtime)

        # 这里'Content-Length'表示剩余待传输的文件字节长度
        if stat.S_ISREG(statobj.st_mode):
            response['Content-Length'] = statobj.st_size - start_bytes

        response['Content-Range'] = 'bytes %s-%s/%s' % (
            start_bytes,  # 起点
            statobj.st_size - 1,  #
            statobj.st_size
        )
        response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
        # 设置默认下载文件名,当下载文件为中文命名时,特殊构造一波
        response['Content-Disposition'] = "attachment;filename={}".format(escape_uri_path(file.filename))
        operation = '下载了文件%s' % file.filename
        datas = {}
        datas['operation'] = operation
        datas['user_id'] = user_id
        rec = RecentlySerializer(data=datas)
        if rec.is_valid():
            rec.save()
        else:
            print(rec.errors)
        return response
示例#26
0
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
示例#27
0
def serve(request, path, document_root = None, show_indexes = False, nocache = False):
    """
    Adapted from django.views.static to handle the creation/modification date of the resource's publisher
    instead of only the file's value.
    
    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``.
    """

    # Clean up given path to only allow serving files below document_root.
    path = urllib.unquote(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'
    # XXX TODO: Handle this correctly!!! Disabled to avoid using file mod. time instead of obj mod. time
    if not nocache:
        if not was_modified_since(
            request.META.get(
                'HTTP_IF_MODIFIED_SINCE'),
                    statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]
        ):
            return HttpResponseNotModified(mimetype=mimetype)
            
    # XXX This is subsubsuboptimal!
    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
示例#28
0
def download(request, path, document_root=None):
    """
    Modificata di django.views.static.serve per far fare il download da apache

    To use, put a URL pattern such as::

        (r'^xsendfile/(?P<path>.*)$', 'admintools.views.xsendfile', {'document_root' : '/path/to/my/files/'})
        
        return
    la document_root di default e' settings.MEDIA_ROOT + '/' + private
    non e' possibile fare il download di un file esterno alla documento_root
    """
    if document_root is None:
        # document_root = os.path.join(
        #    settings.MEDIA_ROOT, 'private'
        #    )
        document_root = '/opt/geoserver_data/data/'
    # 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)
    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'

    # non dovrebbe piu' servire perche' si arrangia X-Sendfile di apache
    #contents = open(fullpath, 'rb').read()
    #response = HttpResponse(contents, mimetype=mimetype)
    response = HttpResponse(mimetype=mimetype)
    response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
    #response["Content-Length"] = len(contents)
    response[
        'Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(
            path)
    response['X-Sendfile'] = smart_str(fullpath)
    return response
示例#29
0
def not_modified(request, img):
    """
    (Code stolen from the static file view.)
    """
    from django.views.static import was_modified_since

    if not was_modified_since(request.META.get("HTTP_IF_MODIFIED_SINCE"), img.statobj[stat.ST_MTIME], 0):
        return HttpResponseNotModified()
    raise WasModified()
示例#30
0
def download(request, path, document_root=None):
    """
    Modificata di django.views.static.serve per far fare il download da apache

    To use, put a URL pattern such as::

        (r'^xsendfile/(?P<path>.*)$', 'admintools.views.xsendfile', {'document_root' : '/path/to/my/files/'})
        
        return
    la document_root di default e' settings.MEDIA_ROOT + '/' + private
    non e' possibile fare il download di un file esterno alla documento_root
    """
    if document_root is None:
        # document_root = os.path.join(
        #    settings.MEDIA_ROOT, 'private'
        #    )
        document_root = '/opt/geoserver_data/data/'
    # 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)
    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'
    
    # non dovrebbe piu' servire perche' si arrangia X-Sendfile di apache
    #contents = open(fullpath, 'rb').read()
    #response = HttpResponse(contents, mimetype=mimetype)
    response = HttpResponse(mimetype=mimetype)
    response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
    #response["Content-Length"] = len(contents)
    response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(path)
    response['X-Sendfile'] = smart_str(fullpath)
    return response
示例#31
0
def _serve_static(request, fullpath):
    # From Django source code: django/views/static.py
    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
示例#32
0
def _serve_static(request, fullpath):
    # From Django source code: django/views/static.py
    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
示例#33
0
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
示例#34
0
def serve(request, request_path):
    composite = get_composite(request_path)
    statobj = os.stat(composite.src.path)
    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(composite.src.path)
    content_type = content_type or 'application/octet-stream'
    response = FileResponse(composite.src.file, content_type=content_type)
    response["Last-Modified"] = http_date(statobj.st_mtime)
    if encoding:
        response["Content-Encoding"] = encoding
        return response
示例#35
0
def chart_cache(request, eip_id):
    fullpath = _get_chart_to_serve(request, eip_id)
    
    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
示例#36
0
def chart_cache(request, eip_id):
    fullpath = _get_chart_to_serve(request, eip_id)

    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
示例#37
0
def serve(request, path):
    """
    Serve files from default storage.

    To use, put a URL pattern such as::

        (r'^(?P<path>.*)$', 'piplmesh.utils.storage.serve')

    in your URLconf.
    """

    if not settings.DEBUG:
        raise exceptions.ImproperlyConfigured(
            "The view can only be used in debug mode.")
    normalized_path = posixpath.normpath(urllib.unquote(path)).lstrip('/')

    if not storage.default_storage.exists(normalized_path):
        if path.endswith('/') or path == '':
            raise http.Http404("Directory indexes are not allowed here.")
        raise http.Http404("'%s' could not be found" % path)

    try:
        mimetype = storage.default_storage.mimetype(
            normalized_path) or 'application/octet-stream'
    except (NotImplementedError, AttributeError):
        mimetype = 'application/octet-stream'

    try:
        modified_time = time.mktime(
            storage.default_storage.modified_time(normalized_path).timetuple())
    except (NotImplementedError, AttributeError):
        modified_time = None

    size = storage.default_storage.size(normalized_path)

    if modified_time is not None and not static.was_modified_since(
            request.META.get('HTTP_IF_MODIFIED_SINCE'), modified_time, size):
        return http.HttpResponseNotModified(mimetype=mimetype)

    f = storage.default_storage.open(normalized_path, 'rb')
    try:
        response = http.HttpResponse(f.read(), mimetype=mimetype)
    finally:
        f.close()

    response['Content-Length'] = size

    if modified_time is not None:
        response['Last-Modified'] = http_utils.http_date(modified_time)

    return response
示例#38
0
文件: files.py 项目: nirgal/ngw
    def get(self, request, fid, cid, width, height):
        cf = get_object_or_404(ContactField, pk=fid)
        if not perms.c_can_view_fields_cg(request.user.id,
                                          cf.contact_group_id):
            raise PermissionDenied

        fullpath_orig = os.path.join(settings.MEDIA_ROOT, 'fields', fid, cid)
        fullpath_thumb = os.path.join(settings.MEDIA_ROOT, 'fields', fid,
                                      cid + ".{0}x{1}".format(width, height))
        try:
            stat_orig = os.stat(fullpath_orig)
        except FileNotFoundError:
            raise Http404(_('"{path}" does not exist').format(
                path=fullpath_orig))

        try:
            stat_thumb = os.stat(fullpath_thumb)
            thumb_outdated = (stat_thumb.st_mtime < stat_orig.st_mtime)
        except FileNotFoundError:
            thumb_outdated = True

        if thumb_outdated:
            img = Image.open(fullpath_orig)
            width, height = int(width), int(height)
            img.thumbnail((width, height))
            img.save(fullpath_thumb, "JPEG")
            stat_thumb = os.stat(fullpath_thumb)
        else:
            # Respect the If-Modified-Since header.
            if not static.was_modified_since(
               request.META.get('HTTP_IF_MODIFIED_SINCE'),
               stat_thumb.st_mtime, stat_thumb.st_size):
                return HttpResponseNotModified()

        # START OF content_type detection
        cfv = get_object_or_404(ContactFieldValue,
                                contact_id=cid, contact_field_id=fid)
        fileinfo = json.loads(cfv.value)
        content_type = fileinfo['content_type']
        # END OF content_type detection

        response = FileResponse(open(fullpath_thumb, 'rb'),
                                content_type=content_type)
        response["Last-Modified"] = http_date(stat_thumb.st_mtime)
        if stat.S_ISREG(stat_thumb.st_mode):
            response["Content-Length"] = stat_thumb.st_size

        response['Content-Disposition'] = 'inline; filename="{0}"'.format(
            header_encode(fileinfo['filename'].encode('utf-8'), 'utf-8'))
        return response
示例#39
0
def static_media(request, path):
    """
    Taken from django-sentry:
    http://github.com/dcramer/django-sentry

    Serve static files below a given point in the directory structure.
    """
    from django.utils.http import http_date
    from django.views.static import was_modified_since
    import mimetypes
    import os.path
    import posixpath
    import stat
    import urllib

    document_root = os.path.join(settings.ROOT, 'static')
    print 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):
        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
示例#40
0
def static_media(request, path):
    """
    Taken from django-sentry:
    http://github.com/dcramer/django-sentry

    Serve static files below a given point in the directory structure.
    """
    from django.utils.http import http_date
    from django.views.static import was_modified_since
    import mimetypes
    import os.path
    import posixpath
    import stat
    import urllib

    document_root = os.path.join(settings.ROOT, 'static')
    print 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):
        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
示例#41
0
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
示例#42
0
    def wrapper(request, commid=None, *args, **kwargs):
        # Get the fax image object; return 404 if not found
        try:
            img = FaxImage(Fax.objects.visible_to_user(request.user).get(pk=commid))
        except Fax.DoesNotExist:
            raise Http404
        # Try to satisfy conditional GET
        from django.views.static import was_modified_since

        if not was_modified_since(request.META.get("HTTP_IF_MODIFIED_SINCE"), img.statobj[stat.ST_MTIME], 0):
            return HttpResponseNotModified()
        # No, we have to send the full response
        response = func(request, commid=commid, img=img, *args, **kwargs)
        response["Last-Modified"] = rfc822.formatdate(img.statobj[stat.ST_MTIME])
        return response
示例#43
0
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
示例#44
0
 def serve(self, request, path, **kwargs):
     # the following code is largely borrowed from `django.views.static.serve`
     # and django-filetransfers: filetransfers.backends.default
     if not os.path.exists(path):
         raise Http404('"%s" does not exist' % path)
     # Respect the If-Modified-Since header.
     statobj = os.stat(path)
     mimetype = self.get_mimetype(path)
     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)
     with open(path, 'rb') as fd:
         response = HttpResponse(fd.read(), content_type=mimetype)
     response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
     self.default_headers(request=request, response=response, path=path, **kwargs)
     return response
def angular(request, path='index.html', document_root=None):
    path = posixpath.normpath(path).lstrip('/')
    fullpath = Path(safe_join(document_root, path))
    if not fullpath.exists():
        fullpath = Path(safe_join(document_root, 'index.html'))
    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
示例#46
0
 def serve(self, request, file_obj, **kwargs):
     fullpath = file_obj.path
     # the following code is largely borrowed from `django.views.static.serve`
     # and django-filetransfers: filetransfers.backends.default
     if not os.path.exists(fullpath):
         raise Http404('"%s" does not exist' % fullpath)
     # Respect the If-Modified-Since header.
     statobj = os.stat(fullpath)
     mimetype = self.get_mimetype(fullpath)
     if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                               statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
         return HttpResponseNotModified(mimetype=mimetype)
     response = HttpResponse(open(fullpath, 'rb').read(), mimetype=mimetype)
     response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
     self.default_headers(request=request, response=response, file_obj=file_obj, **kwargs)
     return response
示例#47
0
 def serve(self, request, file_obj, **kwargs):
     fullpath = file_obj.path
     # the following code is largely borrowed from `django.views.static.serve`
     # and django-filetransfers: filetransfers.backends.default
     if not os.path.exists(fullpath):
         raise Http404('"%s" does not exist' % fullpath)
     # Respect the If-Modified-Since header.
     statobj = os.stat(fullpath)
     response_params = {'content_type': self.get_mimetype(fullpath)}
     if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                               statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
         return HttpResponseNotModified(**response_params)
     response = HttpResponse(open(fullpath, 'rb').read(), **response_params)
     response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
     self.default_headers(request=request, response=response, file_obj=file_obj, **kwargs)
     return response
示例#48
0
文件: views.py 项目: Wayne1316/game
 def get(self, request, *args, **kwargs):
     if self.path is None:
         self.path = self.get_path()
     if not os.path.exists(self.path):
         raise Http404('"{path}" does not exist'.format(path=self.path))
     stat = os.stat(self.path)
     mimetype, encoding = mimetypes.guess_type(self.path)
     mimetype = mimetype or 'application/octet-stream'
     if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), stat.st_mtime, stat.st_size):
         return HttpResponseNotModified(mimetype - mimetype)
     response = HttpResponse(open(self.path, 'rb').read(), content_type=mimetype)
     response['Last-Modified'] = http_date(stat.st_mtime)
     response['Content-Length'] = stat.st_size
     if encoding:
         response['Content-Encoding'] = encoding
     return response
示例#49
0
    def render_to_response(self, *args, **kwargs):
        condition = getattr(self.object.file, 'condition', None)

        if self.check_modified and not was_modified_since(
                self.request.META.get('HTTP_IF_MODIFIED_SINCE'),
                self.statobj.st_mtime, self.statobj.st_size):
            return HttpResponseNotModified(mimetype=self.mimetype)

        self.get_response()
        self.set_headers()

        signals.pre_download.send(sender=self.model,
                                  instance=self.object,
                                  request=self.request)

        return self.response
示例#50
0
def photo(request, uid):
    now = time.time()
    max_age = 1800
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), now - max_age):
        return HttpResponseNotModified()

    user = get_object_or_404(models.LdapUser, pk=uid)
    if not user.photo:
        return HttpResponseRedirect(granadilla_media('img/unknown.png'))
    response = HttpResponse()
    response['Cache-Control'] = 'max-age=%i' % max_age
    response['Content-Length'] = len(user.photo)
    response['Content-Type'] = 'image/jpeg'
    response['Last-Modified'] = http_date(now)
    response.write(user.photo)
    return response
示例#51
0
def resize(request, path_name, format, url):
    if path_name == 'static_resize':
        prefix = settings.STATIC_ROOT
    elif path_name == 'media_resize':
        prefix = settings.MEDIA_ROOT
    else:
        prefix = settings.IMAGEFIT_ROOT
    # remove prepending slash
    if url[0] == '/':
        url = url[1:]
    # generate Image instance
    if path_name == "external_resize":
        image = Image(path=url)
    else:
        image = Image(path=os.path.join(prefix, url))
        if not os.path.exists(image.path):
            return HttpResponse(status=404)

        statobj = os.stat(image.path)
        if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                                  statobj[stat.ST_MTIME],
                                  statobj[stat.ST_SIZE]):
            return HttpResponseNotModified(content_type=image.mimetype)

    image.cached_name = request.META.get('PATH_INFO')

    if settings.IMAGEFIT_CACHE_ENABLED:
        image.cache = cache
        # shortcut everything, render cached version
        if image.is_cached:
            return _image_response(image)

    # retrieve preset from format argument
    preset = Presets.get(format) or Presets.from_string(format)
    if not preset:
        raise ImproperlyConfigured(
            " \"%s\" is neither a \"WIDTHxHEIGHT\" format nor a key in " +
            "IMAGEFIT_PRESETS." % format)

    # Resize and cache image
    if preset.get('crop'):
        image.crop(preset.get('width'), preset.get('height'))
    else:
        image.resize(preset.get('width'), preset.get('height'))
    image.save()

    return _image_response(image)
示例#52
0
def serve(request, path):
    """
    Serve files from default storage.

    To use, put a URL pattern such as::

        (r'^(?P<path>.*)$', 'piplmesh.utils.storage.serve')

    in your URLconf.
    """

    if not settings.DEBUG:
        raise exceptions.ImproperlyConfigured("The view can only be used in debug mode.")
    normalized_path = posixpath.normpath(urllib.unquote(path)).lstrip('/')

    if not storage.default_storage.exists(normalized_path):
        if path.endswith('/') or path == '':
            raise http.Http404("Directory indexes are not allowed here.")
        raise http.Http404("'%s' could not be found" % path)

    try:
        mimetype = storage.default_storage.mimetype(normalized_path) or 'application/octet-stream'
    except (NotImplementedError, AttributeError):
        mimetype = 'application/octet-stream'

    try:
        modified_time = time.mktime(storage.default_storage.modified_time(normalized_path).timetuple())
    except (NotImplementedError, AttributeError):
        modified_time = None

    size = storage.default_storage.size(normalized_path)

    if modified_time is not None and not static.was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), modified_time, size):
        return http.HttpResponseNotModified(mimetype=mimetype)

    f = storage.default_storage.open(normalized_path, 'rb')
    try:
        response = http.HttpResponse(f.read(), mimetype=mimetype)
    finally:
        f.close()

    response['Content-Length'] = size

    if modified_time is not None:
        response['Last-Modified'] = http_utils.http_date(modified_time)

    return response
示例#53
0
文件: sites.py 项目: limnick/nexus
    def media(self, request, module, path):
        """
        Serve static files below a given point in the directory structure.
        """

        if conf.USE_STATICFILES and serve:
            return serve(request, path='%s/%s' % (module, path))

        if module == 'nexus':
            document_root = os.path.join(NEXUS_ROOT, 'static')
        else:
            document_root = self.get_module(module).media_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):
            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
示例#54
0
    def serve(private_file):
        # Support If-Last-Modified
        mtime = private_file.modified_time.timestamp()
        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.
        response = FileResponse(private_file.open())
        response['Content-Type'] = private_file.content_type
        response['Content-Length'] = size
        response["Last-Modified"] = http_date(mtime)
        return response
示例#55
0
 def serve(self, request, path):
     # the following code is largely borrowed from `django.views.static.serve`
     # and django-filetransfers: filetransfers.backends.default
     fullpath = os.path.join(settings.PRIVATE_MEDIA_ROOT, path)
     if not os.path.exists(fullpath):
         raise Http404('"{0}" does not exist'.format(fullpath))
     # Respect the If-Modified-Since header.
     statobj = os.stat(fullpath)
     content_type = 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=content_type)
     response = HttpResponse(open(fullpath, 'rb').read(), content_type=content_type)
     response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
     # filename = os.path.basename(path)
     # response['Content-Disposition'] = smart_str(u'attachment; filename={0}'.format(filename))
     return response
示例#56
0
 def serve(self, request, path):
     # the following code is largely borrowed from `django.views.static.serve`
     # and django-filetransfers: filetransfers.backends.default
     fullpath = os.path.join(settings.PRIVATE_MEDIA_ROOT, path)
     if not os.path.exists(fullpath):
         raise Http404('"{0}" does not exist'.format(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)
     response = HttpResponse(open(fullpath, 'rb').read(), mimetype=mimetype)
     response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
     # filename = os.path.basename(path)
     # response['Content-Disposition'] = smart_str(u'attachment; filename={0}'.format(filename))
     return response
示例#57
0
def static_media(request, path):
    """
    Serve static files below a given point in the directory structure.
    """

    document_root = os.path.join(settings.ROOT, 'static')

    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):
        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)

    # WARNING: Python 2.6.2 and earlier can crash here with an infinite
    # recursion error when used in a multi-threaded environment, due to a
    # race condition in mimetypes.guess_type.  Either upgrade python,
    # or implement your own guess_type function.
    # Ref: http://bugs.python.org/issue5853
    #      Fixed in r72048
    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
示例#58
0
文件: http.py 项目: kennethlove/dwdj
def file_response(request, filepath,
                  attachment=False, attachment_name=None,
                  mimetype=None, encoding=None):
    statobj = os.stat(filepath)
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj.st_mtime, statobj.st_size):
        return HttpResponseNotModified()

    if mimetype is None:
        mimetype, encoding = mimetypes.guess_type(filepath)
    response = data_response(
        open(filepath, 'rb'), size=statobj.st_size,
        mimetype=mimetype, encoding=encoding,
    )
    response = CompatibleStreamingHttpResponse(open(filepath, 'rb'),
                                               content_type=mimetype)
    response["Last-Modified"] = http_date(statobj.st_mtime)
    return response