Custom Search

Monday, October 7, 2013

Sqlalchemy Decorator to find connection id associated with a Session


from functools import wraps
def find_connection_id_deco(func):
    """
    """
    @wraps(func)
    def wrap1(*args, **kwargs):
        """
        """
        gls = func.__globals__
        _DBSession = gls.get("DBSession")
        if _DBSession:
            res1 = _DBSession.connection().execute("SELECT connection_id()")
            if res1:
                conn_id = res1.fetchone()[0]
                print "===%s===%s()===conn_id_1===%s" %(func.func_code.co_filename, func.__name__, conn_id)
            # ###OR
            # res2 = DBSession.execute("SELECT connection_id();")
            # if res2:
            #     conn_id = res2.fetchone()[0]
            #     print "===%s()===conn_id_2===%s" %(func.__name__, conn_id)
        return func(*args, **kwargs)
    return wrap1

OutPut
=====
===/bla/bla/file1.py===func1()===conn_id_1===1481
===/bla/bla/file2.py===func2()===conn_id_1===1481
===/bla/bla/file3.py===func3()===conn_id_1===1483
===/bla/bla/file4.py===func4()===conn_id_1===1485
===/bla/bla/file5.py===func5()===conn_id_1===1485

#####################

def find_connection_id(msg=""):
    """
    """
    _DBSession = globals().get("DBSession")
    if _DBSession:
        res1 = _DBSession.connection().execute("SELECT connection_id()")
        if res1:
            conn_id = res1.fetchone()[0]
            print "===%s===conn_id_1===%s" %(msg, conn_id)

Note:
====
1) transaction.commit() will close all existing DBSessions and connection associated with it.
*transaction.commit()

2) DBSession.query() followed by a transaction.commit() will start a new DBSession and connection.
*transaction.commit()
*DBSession.query()

2 comments:

  1. def find_connection_id(msg=""):
    """
    """
    _DBSession = globals().get("DBSession")
    if _DBSession:
    res1 = _DBSession.connection().execute("SELECT connection_id()")
    if res1:
    conn_id = res1.fetchone()[0]
    print "===%s===conn_id_1===%s" %(msg, conn_id)

    ReplyDelete