python sqlalchemy session_flask_sqlalchemy的session用法疑问

其实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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值