Skip to content

Add support for db in GridFS functions #178

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 deletions flask_pymongo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,12 @@ def init_app(self, app: Flask, uri: str | None = None, *args: Any, **kwargs: Any

# view helpers
def send_file(
self, filename: str, base: str = "fs", version: int = -1, cache_for: int = 31536000
self,
filename: str,
base: str = "fs",
version: int = -1,
cache_for: int = 31536000,
db: str | None = None,
) -> Response:
"""Respond with a file from GridFS.

Expand All @@ -144,6 +149,7 @@ def get_upload(filename):
revision. If no such version exists, return with HTTP status 404.
:param int cache_for: number of seconds that browsers should be
instructed to cache responses
:param str db: the target database, if different from the default database.
"""
if not isinstance(base, str):
raise TypeError("'base' must be string or unicode")
Expand All @@ -152,8 +158,13 @@ def get_upload(filename):
if not isinstance(cache_for, int):
raise TypeError("'cache_for' must be an integer")

assert self.db is not None, "Please initialize the app before calling send_file!"
storage = GridFS(self.db, base)
if db:
db_obj = self.cx[db]
else:
db_obj = self.db

assert db_obj is not None, "Please initialize the app before calling send_file!"
storage = GridFS(db_obj, base)

try:
fileobj = storage.get_version(filename=filename, version=version)
Expand Down Expand Up @@ -189,6 +200,7 @@ def save_file(
fileobj: Any,
base: str = "fs",
content_type: str | None = None,
db: str | None = None,
**kwargs: Any,
) -> Any:
"""Save a file-like object to GridFS using the given filename.
Expand All @@ -207,6 +219,7 @@ def save_upload(filename):
:param str content_type: the MIME content-type of the file. If
``None``, the content-type is guessed from the filename using
:func:`~mimetypes.guess_type`
:param str db: the target database, if different from the default database.
:param kwargs: extra attributes to be stored in the file's document,
passed directly to :meth:`gridfs.GridFS.put`
"""
Expand All @@ -218,7 +231,11 @@ def save_upload(filename):
if content_type is None:
content_type, _ = guess_type(filename)

assert self.db is not None, "Please initialize the app before calling save_file!"
storage = GridFS(self.db, base)
if db:
db_obj = self.cx[db]
else:
db_obj = self.db
assert db_obj is not None, "Please initialize the app before calling save_file!"
storage = GridFS(db_obj, base)
id = storage.put(fileobj, filename=filename, content_type=content_type, **kwargs)
return id
13 changes: 13 additions & 0 deletions tests/test_gridfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ def test_it_saves_files(self):
gridfs = GridFS(self.mongo.db)
assert gridfs.exists({"filename": "my-file"})

def test_it_saves_files_to_another_db(self):
fileobj = BytesIO(b"these are the bytes")

self.mongo.save_file("my-file", fileobj, db="other")
assert self.mongo.db is not None
gridfs = GridFS(self.mongo.cx["other"])
assert gridfs.exists({"filename": "my-file"})

def test_it_saves_files_with_props(self):
fileobj = BytesIO(b"these are the bytes")

Expand All @@ -56,6 +64,7 @@ def setUp(self):
# make it bigger than 1 gridfs chunk
self.myfile = BytesIO(b"a" * 500 * 1024)
self.mongo.save_file("myfile.txt", self.myfile)
self.mongo.save_file("my_other_file.txt", self.myfile, db="other")

def test_it_404s_for_missing_files(self):
with pytest.raises(NotFound):
Expand All @@ -65,6 +74,10 @@ def test_it_sets_content_type(self):
resp = self.mongo.send_file("myfile.txt")
assert resp.content_type.startswith("text/plain")

def test_it_sends_file_to_another_db(self):
resp = self.mongo.send_file("my_other_file.txt", db="other")
assert resp.content_type.startswith("text/plain")

def test_it_sets_content_length(self):
resp = self.mongo.send_file("myfile.txt")
assert resp.content_length == len(self.myfile.getvalue())
Expand Down
Loading