Django, Nginx and GridFS Con’t

Whew.

Took a little while longer than I anticipated but I have successfully managed to get uploaded files into MongoDB using GridFS and then served through nginx-gridfs in a nifty modal media viewer called Shadowbox.js.

In an earlier post I covered recompiling Nginx in Ubuntu to add the nginx-gridfs module. The steps outlined in that post are necessary before proceeding.

Django Model

As stated earlier, I am using the excellent Django MongoDB Engine which will allow base Django model FileField to upload files directly to GridFS as opposed to the local filesystem. Here is the models.py configuration that worked for me:

from django_mongodb_engine.fields import GridFSField
from django_mongodb_engine.storage import GridFSStorage

gridfs = GridFSStorage()
images = GridFSStorage(location='/gridfs')

Then in your specific model definition, define your FileField (or ImageField) as such:

class Foo(models.Model):
    ...
    file_1 = models.FileField(storage=gridfs, upload_to='gridfs')
    ...

Uploaded files will store the path and filename in the file_1 key/value store. So, bar.jpg would be stored as gridfs/bar.jpg. This is important later on.

Nginx

There are ways of serving files stored in GridFS directly out of Django but it is not recommended. The preferred approach is nginx-gridfs which is fairly easy to configure once you have defined your Django models.

The root_collection parameter is necessary as it assumes that the fs collection is used by default. Django MongoDB Engine appears to use storage.images/storage.files by default so you will need to specify either one in. Second, if you do not specify a field or type value, requests to example.com/gridfs/ will need to use the ObjectID (_id) to retrieve the specific files.

Since the Foo class will store the values using the path and filename, you will not know the ObjectID of the objects through a standard query.

location /gridfs/ {
    gridfs database root_collection=storage.images field=filename type=string;
    mongo 127.0.0.1:27017;
}

Once you restart Nginx, requests to example.com/gridfs/bar.jpg should return the uploaded file.

One thought on “Django, Nginx and GridFS Con’t

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>