Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
pickable mongodb connection object
class PickableCollection(object):
def __init__(self, collection):
super(PickableCollection, self).__setattr__('collection', collection)
def __getattr__(self, k):
return getattr(self.collection, k)
def __setattr__(self, k, v):
return setattr(self.collection, k, v)
def __getitem__(self, k):
return self.collection[k]
def __setitem__(self, k, v):
self.collection[k] = v
def __getstate__(self):
client = self.collection._Collection__database._Database__client
host, port = list(client.nodes)[0]
return {
'name': self.name,
'database': self.database.name,
'host': host,
'port': port,
'credentials': self.database.client._MongoClient__all_credentials[self.database.name],
}
def __setstate__(self, state):
from pymongo import MongoClient
url = 'mongodb://{credentials.username}:{credentials.password}@{host}:{port}/{database}'.format(**state)
client = MongoClient(url, authSource=state['credentials'].source)
db = client.get_database()
collection = db[state['name']]
super(PickableCollection, self).__setattr__('collection', collection)
def __repr__(self):
return 'PickableCollection({})'.format(repr(self.collection))
@miraculixx

This comment has been minimized.

Copy link
Owner Author

commented Apr 30, 2018

note this pickels the full credentials which is not necessarily what you want. easily resolved by taking the credentials from the environment instead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.