我们发现Session与scoped_session都有一些方法:

但是scoped_session的源码里面没有设置这些方法让我们从源码里去窥探下源码在哪里设置了这些方法:

Session里面的方法放在了public_methods里面:

scoped_session的源码里面没有这些方法?:

那它怎么实现这些方法的呢?

我们看到了它的构造方法:

 def __init__(self, session_factory, scopefunc=None):
"""Construct a new :class:`.scoped_session`. :param session_factory: a factory to create new :class:`.Session`
instances. This is usually, but not necessarily, an instance
of :class:`.sessionmaker`.
:param scopefunc: optional function which defines
the current scope. If not passed, the :class:`.scoped_session`
object assumes "thread-local" scope, and will use
a Python ``threading.local()`` in order to maintain the current
:class:`.Session`. If passed, the function should return
a hashable token; this token will be used as the key in a
dictionary in order to store and retrieve the current
:class:`.Session`. """
self.session_factory = session_factory if scopefunc:
self.registry = ScopedRegistry(session_factory, scopefunc)
else:
self.registry = ThreadLocalRegistry(session_factory)

第一次进来时,scopefunc是空的。

走else,

 self.registry = ThreadLocalRegistry(session_factory)
就会实例化:ThreadLocalRegistry。
class ThreadLocalRegistry(ScopedRegistry):
"""A :class:`.ScopedRegistry` that uses a ``threading.local()``
variable for storage. """ def __init__(self, createfunc):
self.createfunc = createfunc
self.registry = threading.local()

里面有两个对象  self.createfunc和registry:

registry是唯一标识,

session加上括号就会执行__call__方法:

因为self.registry.value第一次进入没有值:

所以走except  就是执行self.createfunc()往前找传的值是session_factory那么session_factory是谁呢?就是我们传入的session,也就是实例化了我们的session。

就这就会走下面的方法:

def instrument(name):
def do(self, *args, **kwargs):
return getattr(self.registry(), name)(*args, **kwargs)
return do for meth in Session.public_methods:
setattr(scoped_session, meth, instrument(meth))

方法二:

我们发现

class scoped_session(object):
"""Provides scoped management of :class:`.Session` objects. See :ref:`unitofwork_contextual` for a tutorial. """ session_factory = None
"""The `session_factory` provided to `__init__` is stored in this
attribute and may be accessed at a later time. This can be useful when
a new non-scoped :class:`.Session` or :class:`.Connection` to the
database is needed.""" def __init__(self, session_factory, scopefunc=None):
"""Construct a new :class:`.scoped_session`. :param session_factory: a factory to create new :class:`.Session`
instances. This is usually, but not necessarily, an instance
of :class:`.sessionmaker`.
:param scopefunc: optional function which defines
the current scope. If not passed, the :class:`.scoped_session`
object assumes "thread-local" scope, and will use
a Python ``threading.local()`` in order to maintain the current
:class:`.Session`. If passed, the function should return
a hashable token; this token will be used as the key in a
dictionary in order to store and retrieve the current
:class:`.Session`. """
self.session_factory = session_factory if scopefunc:
self.registry = ScopedRegistry(session_factory, scopefunc)
else:
self.registry = ThreadLocalRegistry(session_factory)

如果我们给

scopefunc传值就会走if语句,
class ScopedRegistry(object):
"""A Registry that can store one or multiple instances of a single
class on the basis of a "scope" function. The object implements ``__call__`` as the "getter", so by
calling ``myregistry()`` the contained object is returned
for the current scope. :param createfunc:
a callable that returns a new object to be placed in the registry :param scopefunc:
a callable that will return a key to store/retrieve an object.
""" def __init__(self, createfunc, scopefunc):
"""Construct a new :class:`.ScopedRegistry`. :param createfunc: A creation function that will generate
a new value for the current scope, if none is present. :param scopefunc: A function that returns a hashable
token representing the current scope (such as, current
thread identifier). """
self.createfunc = createfunc
self.scopefunc = scopefunc
self.registry = {} def __call__(self):
key = self.scopefunc()
try:
return self.registry[key]
except KeyError:
return self.registry.setdefault(key, self.createfunc())

我们看到如果对象加括号就会走__call__方法:

第一次没有值,就会走except,设置并且实例化session。

往下方法和方式一一样啦。

在执行到最后我们要加上一句:

session.remove()
我们来看下这句话做了什么?
    def remove(self):
"""Dispose of the current :class:`.Session`, if present. This will first call :meth:`.Session.close` method
on the current :class:`.Session`, which releases any existing
transactional/connection resources still being held; transactions
specifically are rolled back. The :class:`.Session` is then
discarded. Upon next usage within the same scope,
the :class:`.scoped_session` will produce a new
:class:`.Session` object. """ if self.registry.has():
self.registry().close()
self.registry.clear()

我们进入has看下:

    def has(self):
return hasattr(self.registry, "value")

如果有值就执行close方法。

然后在执行clear方法:

    def clear(self):
try:
del self.registry.value
except AttributeError:
pass

SALALchemy Session与scoped_session的源码分析的更多相关文章

  1. SqlAlchemy 中操作数据库时session和scoped_session的区别(源码分析)

    原生session: from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from sqlalch ...

  2. springMVC源码分析--国际化实现Session和Cookie(二)

    上一篇博客springMVC源码分析--国际化LocaleResolver(一)中我们介绍了springMVC提供的国际化的解决方案,接下来我们根据springMVC提供的解决方案来简单的实现一个多语 ...

  3. [asp.net core 源码分析] 01 - Session

    1.Session文档介绍 毋庸置疑学习.Net core最好的方法之一就是学习微软.Net core的官方文档:https://docs.microsoft.com/zh-cn/aspnet/cor ...

  4. TOMCAT8源码分析——SESSION管理分析(上)

    前言 对于广大java开发者而已,对于J2EE规范中的Session应该并不陌生,我们可以使用Session管理用户的会话信息,最常见的就是拿Session用来存放用户登录.身份.权限及状态等信息.对 ...

  5. Tomcat源码分析——Session管理分析(下)

    前言 在<TOMCAT源码分析——SESSION管理分析(上)>一文中我介绍了Session.Session管理器,还以StandardManager为例介绍了Session管理器的初始化 ...

  6. Tomcat源码分析——Session管理分析(上)

    前言 对于广大java开发者而已,对于J2EE规范中的Session应该并不陌生,我们可以使用Session管理用户的会话信息,最常见的就是拿Session用来存放用户登录.身份.权限及状态等信息.对 ...

  7. 一个由正则表达式引发的血案 vs2017使用rdlc实现批量打印 vs2017使用rdlc [asp.net core 源码分析] 01 - Session SignalR sql for xml path用法 MemCahe C# 操作Excel图形——绘制、读取、隐藏、删除图形 IOC,DIP,DI,IoC容器

    1. 血案由来 近期我在为Lazada卖家中心做一个自助注册的项目,其中的shop name校验规则较为复杂,要求:1. 英文字母大小写2. 数字3. 越南文4. 一些特殊字符,如“&”,“- ...

  8. Flask框架(三)—— 请求扩展、中间件、蓝图、session源码分析

    Flask框架(三)—— 请求扩展.中间件.蓝图.session源码分析 目录 请求扩展.中间件.蓝图.session源码分析 一.请求扩展 1.before_request 2.after_requ ...

  9. Flask框架(五) —— session源码分析

    Flask框架(五) —— session源码分析 目录 session源码分析 1.请求来了,执行__call__方法 2.__call__方法 3.调用__call__方法 3.1.ctx = s ...

随机推荐

  1. spring-boot-2.0.3应用篇 - shiro集成

    前言 上一篇:spring-boot-2.0.3源码篇 - 国际化,讲了如何实现国际化,实际上我工作用的模版引擎是freemaker,而不是thymeleaf,不过原理都是相通的. 接着上一篇,这一篇 ...

  2. Angular2入门:TypeScript的类型 - 对象解构

  3. c语言中阶乘的精确值

    对于大数的操作,可能超出int,甚至long的表示范围,对此,可以使用数组来存储大数,下列代码为求1000以内数的阶乘的代码,代码如下: #include <stdio.h> #inclu ...

  4. css中的float属性以及清除方法 (2011-09-03 17:36:26)

    CSS里面的浮动属性是布局的常用工具,只有真正了解它并熟练使用才能将它的优点发挥到极致. 许多页面中都有文字绕图效果,并且各区块分布得错落有置,很多朋友在自学CSS布局时为了做出这些效果往往会被div ...

  5. MVC架构介绍-事件机制

    实例产品基于asp.net mvc 5.0框架,源码下载地址:http://www.jinhusns.com/Products/Download 在.net框架中,事件是将事件发送者(触发事件的对象) ...

  6. webpack4 系列教程(六): 处理SCSS

    这节课讲解webpack4中处理scss.只需要在处理css的配置上增加编译scss的 LOADER 即可.了解更多处理css的内容 >>> >>> 本节课源码 & ...

  7. session一致性架构设计

    什么是session? 由于HTTP协议是无状态的协议,因此它不会去记住上一次浏览器访问服务器时的信息.同一个用户的两次操作,与两个不同用户的操作,对它来说是一样的. 这样虽然满足了互联网web应用的 ...

  8. Team Foundation Server 2013 KEY(密钥)

    isual Studio Ultimate 2013 KEY(密钥):BWG7X-J98B3-W34RT-33B3R-JVYW9 Visual Studio Premium 2013 KEY(密钥): ...

  9. Chrome中无法断点调试的解决方案

    chrome的调试功能实在是太强大了,相比之下ie的就是一垃圾. 最近在调试时出现一种情况,死活不能设置断点,也不能跟踪调试,这下抓狂了. JS也是非常简单的,也没有压缩.为什么就不能调试呢? 网上狂 ...

  10. python 提取linux的硬件信息

    1.代码实现目的 注:代码可以直接粘贴使用 为了实现对主机的整体有明确的了解,实现了下面的代码功能 代码主要功能是: 提取到主机的内存.硬盘.CPU.型号等信息 插入到mysql的数据库中 2.代码具 ...