Could someone please explain, Howto sqlalchemy creating new Session and
connection inside the thread.
Please check the attached programme and output.

I went through the doc
http://docs.sqlalchemy.org/en/latest/orm/session.html#thread-local-scope

and find that sqlalchemy using "threading.local()" to do this magic, but I
could not seen any thing in "threading.local()" (see output of the
programme)



*####### Test Code and Output #######*

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

e = create_engine("mysql://root:xxxxx@localhost/xxxxx")
Session = scoped_session(sessionmaker(e))

import threading
from functools import wraps
def find_connection_id_deco(func):
    """
    """
    @wraps(func)
    def wrap1(*args, **kwargs):
        """
        """
        gls = func.__globals__
        _DBSession = gls.get("Session")
        if _DBSession:
            res1 = _DBSession.connection().execute("SELECT connection_id()")
            if res1:
                conn_id = res1.fetchone()[0]
                print "@@@@%s===%s()===conn_id_1===%s===%s===%s===%s===" \
                %(func.func_code.co_filename, func.__name__, conn_id,
vars(threading.local()),\
                    threading.currentThread().getName(),
threading.currentThread().ident)
        return func(*args, **kwargs)
    return wrap1


@find_connection_id_deco
def test1():
    """
    """
    print "test1"


@find_connection_id_deco
def test2():
    """
    """
    print "test2"



from threading import Thread
test1()
thread = Thread(target=test2)
thread.start()


*OUTPUT
#######*
@@@@cvt_test_script.py===test1()===conn_id_1===661==={}===MainThread===139917239523072===
test1
@@@@cvt_test_script.py===test2()===conn_id_1===662==={}===Thread-1===139917193123584===
test2



Regards
Saju Madhavan
+91 09535134654
_______________________________________________
BangPypers mailing list
BangPypers@python.org
https://mail.python.org/mailman/listinfo/bangpypers

Reply via email to