其实flask_sqlalchemy中使用session之前也是做了session实例化的,只不过这个动作通过proxy的编程技巧被隐藏在scoped_session类中了。《sqlalchemy 1.4 Documentation》中会话章节有提及这种隐式方法访问:
Session = scoped_session(some_factory)
# equivalent to:
#
# session = Session()
# print(session.query(MyClass).all())
#
print(Session.query(MyClass).all())
flask_sqlalchemy帮助使用者简化了session实例化的过程,具体的做法是通过scoped_session._call_ 这个魔术函数来自动完成session实例化的,这里是代码实现片段:
class scoped_session(object):
def __call__(self, **kw):
r"""Return the current :class:`.Session`, creating it
using the :attr:`.scoped_session.session_factory` if not present.
:param **kw: Keyword arguments will be passed to the
:attr:`.scoped_session.session_factory` callable, if an existing
:class:`.Session` is not present. If the :class:`.Session` is present
and keyword arguments have been passed,
:exc:`~sqlalchemy.exc.InvalidRequestError` is raised.
"""
if kw:
if self.registry.has():
raise sa_exc.InvalidRequestError(
"Scoped session is already present; "
"no new arguments may be specified."
)
else:
sess = self.session_factory(**kw)
self.registry.set(sess)
return sess
else:
return self.registry()