From 169ec824dc4bd07327f2fb4cf97e96124fa1cc8d Mon Sep 17 00:00:00 2001 From: Mike Dirolf Date: Tue, 22 Jun 2010 10:51:04 -0400 Subject: [PATCH] add GridFS.exists method PYTHON-132 --- gridfs/__init__.py | 37 +++++++++++++++++++++++++++++++++++++ test/test_gridfs.py | 25 +++++++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/gridfs/__init__.py b/gridfs/__init__.py index 21b6458f8..48627cd81 100644 --- a/gridfs/__init__.py +++ b/gridfs/__init__.py @@ -178,6 +178,43 @@ class GridFS(object): """ return self.__files.distinct("filename") + def exists(self, document_or_id=None, **kwargs): + """Check if a file exists in this instance of :class:`GridFS`. + + The file to check for can be specified by the value of it's + ``_id`` key, or by passing in a query document. A query + document can be passed in as dictionary, or by using keyword + arguments. Thus, the following three calls are equivalent: + + >>> fs.exists(file_id) + >>> fs.exists({"_id": file_id}) + >>> fs.exists(_id=file_id) + + As are the following two calls: + + >>> fs.exists({"filename": "mike.txt"}) + >>> fs.exists(filename="mike.txt") + + And the following two: + + >>> fs.exists({"foo": {"$gt": 12}}) + >>> fs.exists(foo={"$gt": 12}) + + Returns ``True`` if a matching file exists, ``False`` + otherwise. + + :Parameters: + - `document_or_id` (optional): query document, or _id of the + document to check for + - `**kwargs` (optional): keyword arguments are used as a + query document, if they're present. + + .. versionadded:: 1.7+ + """ + if kwargs: + return self.__files.find_one(kwargs) is not None + return self.__files.find_one(document_or_id) is not None + def open(self, *args, **kwargs): """No longer supported. diff --git a/test/test_gridfs.py b/test/test_gridfs.py index b188c67a5..444dd6e7a 100644 --- a/test/test_gridfs.py +++ b/test/test_gridfs.py @@ -187,6 +187,31 @@ class TestGridfs(unittest.TestCase): oid = self.fs.put("hello") self.assertRaises(FileExists, self.fs.put, "world", _id=oid) + def test_exists(self): + oid = self.fs.put("hello") + self.assert_(self.fs.exists(oid)) + self.assert_(self.fs.exists({"_id": oid})) + self.assert_(self.fs.exists(_id=oid)) + + self.failIf(self.fs.exists(filename="mike")) + self.failIf(self.fs.exists("mike")) + + oid = self.fs.put("hello", filename="mike", foo=12) + self.assert_(self.fs.exists(oid)) + self.assert_(self.fs.exists({"_id": oid})) + self.assert_(self.fs.exists(_id=oid)) + self.assert_(self.fs.exists(filename="mike")) + self.assert_(self.fs.exists({"filename": "mike"})) + self.assert_(self.fs.exists(foo=12)) + self.assert_(self.fs.exists({"foo": 12})) + self.assert_(self.fs.exists(foo={"$gt": 11})) + self.assert_(self.fs.exists({"foo": {"$gt": 11}})) + + self.failIf(self.fs.exists(foo=13)) + self.failIf(self.fs.exists({"foo": 13})) + self.failIf(self.fs.exists(foo={"$gt": 12})) + self.failIf(self.fs.exists({"foo": {"$gt": 12}})) + if __name__ == "__main__": unittest.main()