建立會話
一個會話通常使用獲得 sessionmaker ,它建立了一個 Session 類獨特的應用程式。最常見的是,Session 類繫結到引擎,允許例項隱式使用引擎。
from sqlalchemy.orm import sessionmaker
# Initial configuration arguments
Session = sessionmaker(bind=engine)
engine 和 Session 只能建立一次。
會話是我們建立的類的例項:
# This session is bound to provided engine
session = Session()
Session.configure() 可用於稍後配置類,例如應用程式啟動而不是匯入時間。
Session = sessionmaker()
# later
Session.configure(bind=engine)
傳遞給 Session 的引數直接覆蓋傳遞給 sessionmaker 的引數。
session_bound_to_engine2 = Session(bind=engine2)