Created
May 20, 2014 09:41
-
-
Save lig/28d49d4c4a58ad87ed8a to your computer and use it in GitHub Desktop.
Retrieve file from GridFS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http.response import (Http404, HttpResponseNotModified, | |
CompatibleStreamingHttpResponse) | |
from django.utils.http import http_date | |
from django.views.static import was_modified_since | |
from gridfs import GridFS | |
from mongoengine.connection import get_db | |
from bson.objectid import ObjectId | |
def file(request, collection_name, grid_id): | |
fs = GridFS(get_db(), collection_name) | |
oid = ObjectId(grid_id) | |
if not fs.exists(oid): | |
raise Http404() | |
gridout = fs.get(oid) | |
mtime = gridout.upload_date.timestamp() | |
length = gridout.length | |
if gridout.content_type: | |
content_type = gridout.content_type | |
elif gridout.format: | |
content_type = 'image.{}'.format(gridout.format).lower() | |
else: | |
content_type = 'application/octet-stream' | |
# Respect the If-Modified-Since header. | |
if not was_modified_since( | |
request.META.get('HTTP_IF_MODIFIED_SINCE'), mtime, length): | |
return HttpResponseNotModified() | |
response = CompatibleStreamingHttpResponse( | |
gridout, content_type=content_type) | |
response["Last-Modified"] = http_date(mtime) | |
response["Content-Length"] = length | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment