首页 > 数据库 >SQLAlchemy scoped_session

SQLAlchemy scoped_session

时间:2023-12-22 11:13:27浏览次数:40  
标签:SQLAlchemy https self object session 线程 registry scoped

SQLAlchemy scoped_session

本身 session 不是线程安全的。

 

https://docs.sqlalchemy.org/en/14/orm/contextual.html

The object is the scoped_session object, and it represents a registry of Session objects. If you’re not familiar with the registry pattern, a good introduction can be found in Patterns of Enterprise Architecture.

引入注册器,所有线程都可以访问注册器, 注册器内部使用线程local存储 线程自身的session, 从而隔离不同线程

ScopedRegistry

A Registry that can store one or multiple instances of a single class on the basis of a “scope” function.

ThreadLocalRegistry

A ScopedRegistry that uses a threading.local() variable for storage.

 

注册器概念

https://martinfowler.com/eaaCatalog/registry.html

Registry

A well-known object that other objects can use to find common objects and services.

For a full description see P of EAA page 480

When you want to find an object you usually start with another object that has an association to it, and use the association to navigate to it. Thus, if you want to find all the orders for a customer, you start with the customer object and use a method on it to get the orders. However, in some cases you won't have an appropriate object to start with. You may know the customer's ID number but not have a reference. In this case you need some kind of lookup method - a finder - but the question remains: How do you get to the finder?

A Registry is essentially a global object, or at least it looks like one - even if it isn't as global as it may appear.

 

注册器实现代码

https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/util/_collections.py#L663

class ThreadLocalRegistry(ScopedRegistry[_T]):
    """A :class:`.ScopedRegistry` that uses a ``threading.local()``
    variable for storage.

    """

    def __init__(self, createfunc: Callable[[], _T]):
        self.createfunc = createfunc
        self.registry = threading.local()

    def __call__(self) -> _T:
        try:
            return self.registry.value  # type: ignore[no-any-return]
        except AttributeError:
            val = self.registry.value = self.createfunc()
            return val

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

    def set(self, obj: _T) -> None:
        self.registry.value = obj

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

 

参考:

https://farer.org/2017/10/28/sqlalchemy_scoped_session/

https://juejin.cn/post/6844904164141580302

https://www.cnblogs.com/randysun/p/15518306.html

 

标签:SQLAlchemy,https,self,object,session,线程,registry,scoped
From: https://www.cnblogs.com/lightsong/p/17920829.html

相关文章

  • Cookie 和 session 的区别
    Cookie和session的区别参考回答:HTTP是一个无状态协议,因此Cookie的最大的作用就是存储sessionId用来唯一标识用户。一句话概括RESTFUL参考回答:就是用URL定位资源,用HTTP描述操作。讲讲viewport和移动端布局参考回答:可以参考这篇文章:响应式布局的常用......
  • cookie和session的一些疑惑以及ai解答
    我:那么当浏览器关闭的时候,当再次访问这个地址的时候,为什么之前设置的cookie没有被删除掉?而且按照你说的这次可能会生成一个新的sessionID,那么cookie里面的其他数据,它是如何获取上一次的cookie的信息,而且它是如何知道是这个客户端访问的?而不是其他客户端?AI:当浏览器关闭时,是否删......
  • requests模块-session
    session对象能够跨http请求保持某些参数importrequestss=requests.Session()#设置cookiess.get("http://httpbin.org/cookies/set/sessioncookie/123456789")#发送请求,查看当前请求的cookiesr=s.get("http://httpbin.org/cookies")print(r.text)运行结果{"co......
  • Javaweb | 状态管理:Session、Cookie
    ......
  • js Cookie、sessionStorage、localStorage 的区别
    fetch发送2次请求的原因参考回答:fetch发送post请求的时候,总是发送2次,第一次状态码是204,第二次才成功?原因很简单,因为你用fetch的post请求的时候,导致fetch第一次发送了一个Options请求,询问服务器是否支持修改的请求头,如果服务器支持,则在第二次中发送真正的请求......
  • SpringSession+SpringSecurity中如何保存Authentication到Session中的Attribute
     org.springframework.security.web.context.SecurityContextPersistenceFilter#doFilter(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,javax.servlet.FilterChain) org.springframework.security.web.context.HttpSessionSecurityC......
  • SpringSession中的sessionId什么时候会过期
    使用SpringSession后,每次请求后,都会把期间变更的attribute保存到redis中。每次访问都会修改lastAccessTimeorg.springframework.session.web.http.SessionRepositoryFilter#doFilterInternal org.springframework.session.data.redis.RedisIndexedSessionRepository.RedisSes......
  • vue3中的样式为什么加上scoped不生效
    <style>标签添加scoped属性时,Vue会自动为该组件内的所有元素添加一个独特的数据属性,例如data-v-f3f3eg9。同时,它也会修改你的CSS选择器,使得它们只匹配带有这个独特数据属性的元素。这样做的目的是为了确保样式只应用于当前组件内的元素,避免影响到其他组件。然而,当你尝试覆盖子组......
  • Session
     Java中的Session是一种用于跟踪用户状态(根据session是否存在信息判断登录状态)和在多个请求之间共享数据(存在session对象的信息)的机制。用户短信验证码登录是基于sesion登录的,发请求访问Tomcat的时候,sessionid已经自动写到cookie中,以后再请求都会带着这个sessionid,就可以找......
  • style中通过import引入样式时,scoped不生效
    通过import引入的外部css文件,这种引入方式是全局的,也会影响其他组件的页面样式<stylelang="scss"scoped>@importurl(../style.scss);</style>此时虽然用了scoped,但是样式还是全局的。造成样式污染的案例:(1)、父页面中引入css文件<stylescoped>@import"~@/assets/sty......