Last active
December 17, 2015 18:39
-
-
Save diegows/5654284 to your computer and use it in GitHub Desktop.
A proposal for MongoEngine-extra (or may be MongoEngine itself) to support global DB switch per thread.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CSDocument(object): | |
_collections = defaultdict(lambda: None) | |
active_db = None | |
@classmethod | |
def switch_active_db(cls, dbname): | |
cls.active_db = dbname | |
@classmethod | |
def _get_db(cls): | |
return get_db(cls.active_db) | |
@classmethod | |
def _build_key(cls, collection_name): | |
thread_id = threading.currentThread().ident | |
key = '%s-%s-%s' % (thread_id, cls.active_db, collection_name) | |
return key | |
@classmethod | |
def _get_collection(cls): | |
"""Custom MongoEngine function to support global DB switch thread-safe. | |
TODO: add support for capped collections. | |
""" | |
collection_name = cls._get_collection_name() | |
key = cls._build_key(collection_name) | |
if cls._collections[key] is None: | |
db = cls._get_db() | |
cls._collection = db[collection_name] | |
cls._collections[key] = db[collection_name] | |
if cls._meta.get('auto_create_index', True): | |
cls.ensure_indexes() | |
return cls._collections[key] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment