11import os
2+ import urlparse
23
34from gridfs import GridFS , NoFile
45
56from django .core .exceptions import ImproperlyConfigured
67from django .core .files .storage import Storage
8+ from django .utils .encoding import filepath_to_uri
9+
710
811def _get_subcollections (collection ):
912 """
@@ -15,6 +18,7 @@ def _get_subcollections(collection):
1518 if cleaned != collection .name and cleaned .startswith (collection .name ):
1619 yield cleaned
1720
21+
1822class GridFSStorage (Storage ):
1923 """
2024 GridFS Storage backend for Django.
@@ -39,15 +43,24 @@ class GridFSStorage(Storage):
3943 :param database:
4044 Alias of the Django database to use. Defaults to 'default' (the default
4145 Django database).
46+ :param base_url:
47+ URL that serves the files in GridFS (for instance, through nginx-gridfs).
48+ Defaults to None (file not accessible through a URL).
4249 """
4350
44- def __init__ (self , location = '' , collection = 'storage' , database = 'default' ):
51+ def __init__ (self , location = '' , collection = 'storage' , database = 'default' ,
52+ base_url = None ):
4553 self .location = location .strip (os .sep )
4654 self .collection = collection
4755 self .database = database
56+ self .base_url = base_url
57+
4858 if not self .collection :
4959 raise ImproperlyConfigured ("'collection' may not be empty" )
5060
61+ if self .base_url and not self .base_url .endswith ('/' ):
62+ raise ImproperlyConfigured ("If set, 'base_url' must end with a slash" )
63+
5164 def _open (self , path , mode = 'rb' ):
5265 """
5366 Returns a :class:`~gridfs.GridOut` file opened in `mode`, or raises
@@ -104,6 +117,11 @@ def size(self, path):
104117 gridfs , filename = self ._get_gridfs (path )
105118 return gridfs .get_last_version (filename = filename ).length
106119
120+ def url (self , name ):
121+ if self .base_url is None :
122+ raise ValueError ("This file is not accessible via a URL." )
123+ return urlparse .urljoin (self .base_url , filepath_to_uri (name ))
124+
107125 def created_time (self , path ):
108126 """
109127 Returns the datetime the file at `path` was created.
0 commit comments