Created
March 30, 2020 10:57
-
-
Save oduvan/314d60f3098827693ecead573f8a8c02 to your computer and use it in GitHub Desktop.
Switch django default connection inside of context. It is very useful when you use readonly replica in Jupyter for analytics, but time to time you need to implement changes in master db
This file contains hidden or 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
from contextlib import ContextDecorator | |
from django.db import connections | |
class overwrite_default_connection(ContextDecorator): | |
prev_default = None | |
write_connection = None | |
def __init__(self, write_connection): | |
self.write_connection = write_connection | |
def __enter__(self): | |
self.prev_default = connections['default'] | |
connections['default'] = connections[self.write_connection] | |
return self | |
def __exit__(self, *exc): | |
connections['default'] = self.prev_default | |
return False | |
# with overwrite_default_connection('master_py'): | |
# print('Do something with master connection') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment