Skip to content

Instantly share code, notes, and snippets.

@stratomancer
Forked from bruth/gist:7467130
Created July 31, 2014 12:20
Show Gist options
  • Select an option

  • Save stratomancer/659204ef8b6c9f9396ee to your computer and use it in GitHub Desktop.

Select an option

Save stratomancer/659204ef8b6c9f9396ee to your computer and use it in GitHub Desktop.

Revisions

  1. @bruth bruth revised this gist Nov 14, 2013. 1 changed file with 4 additions and 4 deletions.
    8 changes: 4 additions & 4 deletions gistfile1.py
    Original file line number Diff line number Diff line change
    @@ -36,10 +36,10 @@ def __exit__(self, *excinfo):
    self.connection.close()
    del connections.databases[self.alias]

    def adhoc_db_decorator(*args, **kwargs):
    def adhoc_db_decorator(settings, alias=None):
    def decorator(func):
    with adhoc_db(*args, **kwargs):
    def inner(*args, **kwargs):
    def inner(*args, **kwargs):
    with adhoc_db(settings, alias):
    return func(*args, **kwargs)
    return inner
    return inner
    return decorator
  2. @bruth bruth revised this gist Nov 14, 2013. 1 changed file with 6 additions and 0 deletions.
    6 changes: 6 additions & 0 deletions gistfile1.py
    Original file line number Diff line number Diff line change
    @@ -10,6 +10,12 @@ class adhoc_db(object):
    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:
  3. @bruth bruth created this gist Nov 14, 2013.
    39 changes: 39 additions & 0 deletions gistfile1.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    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`.
    """
    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(*args, **kwargs):
    def decorator(func):
    with adhoc_db(*args, **kwargs):
    def inner(*args, **kwargs):
    return func(*args, **kwargs)
    return inner
    return decorator