1
1
import os
2
+ import urlparse
2
3
3
4
from gridfs import GridFS , NoFile
4
5
5
6
from django .core .exceptions import ImproperlyConfigured
6
7
from django .core .files .storage import Storage
8
+ from django .utils .encoding import filepath_to_uri
9
+
7
10
8
11
def _get_subcollections (collection ):
9
12
"""
@@ -15,6 +18,7 @@ def _get_subcollections(collection):
15
18
if cleaned != collection .name and cleaned .startswith (collection .name ):
16
19
yield cleaned
17
20
21
+
18
22
class GridFSStorage (Storage ):
19
23
"""
20
24
GridFS Storage backend for Django.
@@ -39,15 +43,24 @@ class GridFSStorage(Storage):
39
43
:param database:
40
44
Alias of the Django database to use. Defaults to 'default' (the default
41
45
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).
42
49
"""
43
50
44
- def __init__ (self , location = '' , collection = 'storage' , database = 'default' ):
51
+ def __init__ (self , location = '' , collection = 'storage' , database = 'default' ,
52
+ base_url = None ):
45
53
self .location = location .strip (os .sep )
46
54
self .collection = collection
47
55
self .database = database
56
+ self .base_url = base_url
57
+
48
58
if not self .collection :
49
59
raise ImproperlyConfigured ("'collection' may not be empty" )
50
60
61
+ if self .base_url and not self .base_url .endswith ('/' ):
62
+ raise ImproperlyConfigured ("If set, 'base_url' must end with a slash" )
63
+
51
64
def _open (self , path , mode = 'rb' ):
52
65
"""
53
66
Returns a :class:`~gridfs.GridOut` file opened in `mode`, or raises
@@ -104,6 +117,11 @@ def size(self, path):
104
117
gridfs , filename = self ._get_gridfs (path )
105
118
return gridfs .get_last_version (filename = filename ).length
106
119
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
+
107
125
def created_time (self , path ):
108
126
"""
109
127
Returns the datetime the file at `path` was created.
0 commit comments