switch_db alias context manager. Example :: # Register connections register_connection('default', 'mongoenginetest') register_connection('testdb-1', 'mongoenginetest2') class Group(Document): name = StringField() Group(name='test').save()
| 47 | |
| 48 | |
| 49 | class switch_db: |
| 50 | """switch_db alias context manager. |
| 51 | |
| 52 | Example :: |
| 53 | |
| 54 | # Register connections |
| 55 | register_connection('default', 'mongoenginetest') |
| 56 | register_connection('testdb-1', 'mongoenginetest2') |
| 57 | |
| 58 | class Group(Document): |
| 59 | name = StringField() |
| 60 | |
| 61 | Group(name='test').save() # Saves in the default db |
| 62 | |
| 63 | with switch_db(Group, 'testdb-1') as Group: |
| 64 | Group(name='hello testdb!').save() # Saves in testdb-1 |
| 65 | """ |
| 66 | |
| 67 | def __init__(self, cls, db_alias): |
| 68 | """Construct the switch_db context manager |
| 69 | |
| 70 | :param cls: the class to change the registered db |
| 71 | :param db_alias: the name of the specific database to use |
| 72 | """ |
| 73 | self.cls = cls |
| 74 | self.collection = cls._get_collection() |
| 75 | self.db_alias = db_alias |
| 76 | self.ori_db_alias = cls._meta.get("db_alias", DEFAULT_CONNECTION_NAME) |
| 77 | |
| 78 | def __enter__(self): |
| 79 | """Change the db_alias and clear the cached collection.""" |
| 80 | self.cls._meta["db_alias"] = self.db_alias |
| 81 | self.cls._collection = None |
| 82 | return self.cls |
| 83 | |
| 84 | def __exit__(self, t, value, traceback): |
| 85 | """Reset the db_alias and collection.""" |
| 86 | self.cls._meta["db_alias"] = self.ori_db_alias |
| 87 | self.cls._collection = self.collection |
| 88 | |
| 89 | |
| 90 | class switch_collection: |
no outgoing calls