Last active
August 9, 2024 03:40
-
-
Save bruth/7467130 to your computer and use it in GitHub Desktop.
Django adhoc database
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
import string | |
from random import SystemRandom | |
from django.db import connections | |
key_chars = string.ascii_letters | |
random = SystemRandom() | |
class adhoc_db(object): | |
"""Context manager that temporarily adds a database connection. | |
Exceptions are passed through, but ensures the connection and | |
settings have been cleaned up from `connections.databases`. | |
Usage: | |
with adhoc_db(settings) as conn: | |
# do something with... | |
""" | |
def __init__(self, settings, alias=None): | |
if alias is None: | |
key = ''.join(random.choice(key_chars) for i in xrange(10)) | |
# TODO should this lock? | |
assert alias not in connections.databases or \ | |
connections.databases[alias] == settings | |
self.alias = alias | |
connections.databases[alias] = settings | |
self.connection = connections[alias] | |
def __enter__(self): | |
return self.connection | |
def __exit__(self, *excinfo): | |
self.connection.close() | |
del connections.databases[self.alias] | |
def adhoc_db_decorator(settings, alias=None): | |
def decorator(func): | |
def inner(*args, **kwargs): | |
with adhoc_db(settings, alias): | |
return func(*args, **kwargs) | |
return inner | |
return decorator |
I want to use this in a view and have a per view DB. How would that work?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Trying this out in the context of Django 1.8, and seems like the connection may not actually be dropped at the context manager exit:
I'm wondering if
del connections.databases[self.alias]
in line 37 should instead beThanks for this snippet @bruth!