Skip to content

Commit 89a2a29

Browse files
committed
修复flask alchemy应用结束自动关闭session会出错的问题
Signed-off-by: tinybees <a598824322@163.com>
1 parent 74caa22 commit 89a2a29

3 files changed

Lines changed: 15 additions & 4 deletions

File tree

CHANGES.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
## aeclients Changelog
1+
## eclients Changelog
2+
3+
###[1.0.10] - 2021-1-14
4+
5+
#### Changed
6+
- 修复flask alchemy应用结束自动关闭session会出错的问题
27

38
###[1.0.9] - 2020-10-14
49

eclients/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@
1212
from .db_client import *
1313
from .redis_client import *
1414

15-
__version__ = "1.0.9"
15+
__version__ = "1.0.10"

eclients/db_client.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
@software: PyCharm
77
@time: 18-12-25 下午4:58
88
"""
9+
import threading
910
from collections import MutableMapping, MutableSequence
1011
from contextlib import contextmanager
1112
from typing import Dict, List, NoReturn, Union
@@ -93,6 +94,7 @@ def __init__(self, app=None, *, username: str = "root", passwd: str = None, host
9394
self.dialect = dialect
9495
self.msg_zh = None
9596
self.scoped_sessions: Dict[str, scoped_session] = {} # 主要保存其他scope session
97+
self.registry = threading.local() # 当前线程注册bind key
9698

9799
# 这里要用重写的BaseQuery, 根据BaseQuery的规则,Model中的query_class也需要重新指定为子类model,
98100
# 但是从Model的初始化看,如果Model的query_class为None的话还是会设置为和Query一致,符合要求
@@ -154,8 +156,8 @@ def init_app(self, app, username: str = None, passwd: str = None, host: str = No
154156

155157
@app.teardown_appcontext
156158
def shutdown_other_session(response_or_exc):
157-
for _, session_ in self.scoped_sessions.items():
158-
session_.remove()
159+
for bind_key in getattr(self.registry, "bind_keys", set()):
160+
self.scoped_sessions[bind_key].remove()
159161
return response_or_exc
160162

161163
def get_engine(self, app=None, bind=None):
@@ -231,6 +233,10 @@ def gen_session(self, bind_key: str, session_options: Dict = None) -> Session:
231233
session = self.scoped_sessions[bind_key]()
232234
session.bind_key = bind_key # 设置bind key
233235
session = self.ping_session(session) # 校验重连,保证可用
236+
# 加入当前线程bindkey,用于自动关闭处理
237+
if hasattr(self.registry, "bind_keys") is False:
238+
self.registry.bind_keys = set()
239+
self.registry.bind_keys.add(bind_key)
234240

235241
return session
236242

0 commit comments

Comments
 (0)