@@ -123,7 +123,12 @@ def init_app(self, app: Flask, uri: str | None = None, *args: Any, **kwargs: Any
123
123
124
124
# view helpers
125
125
def send_file (
126
- self , filename : str , base : str = "fs" , version : int = - 1 , cache_for : int = 31536000
126
+ self ,
127
+ filename : str ,
128
+ base : str = "fs" ,
129
+ version : int = - 1 ,
130
+ cache_for : int = 31536000 ,
131
+ db : str | None = None ,
127
132
) -> Response :
128
133
"""Respond with a file from GridFS.
129
134
@@ -144,6 +149,7 @@ def get_upload(filename):
144
149
revision. If no such version exists, return with HTTP status 404.
145
150
:param int cache_for: number of seconds that browsers should be
146
151
instructed to cache responses
152
+ :param str db: the target database, if different from the default database.
147
153
"""
148
154
if not isinstance (base , str ):
149
155
raise TypeError ("'base' must be string or unicode" )
@@ -152,8 +158,13 @@ def get_upload(filename):
152
158
if not isinstance (cache_for , int ):
153
159
raise TypeError ("'cache_for' must be an integer" )
154
160
155
- assert self .db is not None , "Please initialize the app before calling send_file!"
156
- storage = GridFS (self .db , base )
161
+ if db :
162
+ db_obj = self .cx [db ]
163
+ else :
164
+ db_obj = self .db
165
+
166
+ assert db_obj is not None , "Please initialize the app before calling send_file!"
167
+ storage = GridFS (db_obj , base )
157
168
158
169
try :
159
170
fileobj = storage .get_version (filename = filename , version = version )
@@ -189,6 +200,7 @@ def save_file(
189
200
fileobj : Any ,
190
201
base : str = "fs" ,
191
202
content_type : str | None = None ,
203
+ db : str | None = None ,
192
204
** kwargs : Any ,
193
205
) -> Any :
194
206
"""Save a file-like object to GridFS using the given filename.
@@ -207,6 +219,7 @@ def save_upload(filename):
207
219
:param str content_type: the MIME content-type of the file. If
208
220
``None``, the content-type is guessed from the filename using
209
221
:func:`~mimetypes.guess_type`
222
+ :param str db: the target database, if different from the default database.
210
223
:param kwargs: extra attributes to be stored in the file's document,
211
224
passed directly to :meth:`gridfs.GridFS.put`
212
225
"""
@@ -218,7 +231,11 @@ def save_upload(filename):
218
231
if content_type is None :
219
232
content_type , _ = guess_type (filename )
220
233
221
- assert self .db is not None , "Please initialize the app before calling save_file!"
222
- storage = GridFS (self .db , base )
234
+ if db :
235
+ db_obj = self .cx [db ]
236
+ else :
237
+ db_obj = self .db
238
+ assert db_obj is not None , "Please initialize the app before calling save_file!"
239
+ storage = GridFS (db_obj , base )
223
240
id = storage .put (fileobj , filename = filename , content_type = content_type , ** kwargs )
224
241
return id
0 commit comments