I am playing around with mongodb (GridFS) to store files (zip) and try to retrieve them using python`s "pymongo" but its not working as expected i am not able to understand how to retrieve the file(s) i have addedd ...
Below is the code i ran from IDLE ( Python 3.4.1 )
>>> db = Connection(port=31000, host="localhost").fs
>>> db.name
'fs'
>>> db.validate_collection
<bound method Database.validate_collection of Database(Connection('localhost', 31000), 'fs')>
>>> blob_store = gridfs.GridFS(db, collection='bstore')
>>> local_db = dict()
>>> k = r'd:\test\my-scripts.zip'
>>> local_db[k] = blob_store.put(open(k, 'rb'))
[** File is saved, i checked using robomongo **]
>>> blob_store.exists(filename=k)
False
>>> blob_store.exists("53da7cb1b3b44b13e0e27721")
False
>>> local_db
{'d:\\test\\my-scripts.zip': ObjectId('53da7cb1b3b44b13e0e27721')}
>>> blob_store.list()
[]
>>> b = gridfs.GridFS(db, collection='bstore.files')
>>> b.list()
[]
>>> x = blob_store.get(Objectid("53da7cb1b3b44b13e0e27721"))
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
x = blob_store.get(Objectid("53da7cb1b3b44b13e0e27721"))
NameError: name 'Objectid' is not defined
>>> local_db
{'d:\\test\\my-scripts.zip': ObjectId('53da7fd0b3b44b13e0e2772a')}
>>> blob_store.find()
<gridfs.grid_file.GridOutCursor object at 0x0000000003DC1828>
>>> a = blob_store.find(ObjectId("53da7fd0b3b44b13e0e2772a"))
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
a = blob_store.find(ObjectId("53da7fd0b3b44b13e0e2772a"))
NameError: name 'ObjectId' is not defined
Now i am not sure how to retrieve the file from mongo? am i missing something obvious?
Thanks
To get all the Documents of the Collection use find() method. The find() method takes a query object as a parameter if we want to find all documents then pass none in the find() method.
Tornado is an asynchronous Python web framework, and PyMongo is a blocking driver for MongoDB. Obviously, any lengthy PyMongo operation blocks the event loop and hobbles its throughput.
The find_One() method of pymongo is used to retrieve a single document based on your query, in case of no matches this method returns nothing and if you doesn't use any query it returns the first document of the collection.
PyMongo is thread-safe and even provides built-in connection pooling for threaded applications.
You need to import the ObjectId symbol:
from bson import ObjectId
Then your code should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With