python - SQLAlchemy 连接池和 session

标签 python session flask sqlalchemy connection-pooling

我最近开始使用 SQLAlchemy 并试图了解 connection poolsessionweb-应用程序

我正在使用 flask 构建一个 API

__init__.py

engine = create_engine('mysql://username:password@localhost/my_database') 
DBSession = sessionmaker(bind=engine)

views.py

@app.route('/books', methods = ['GET'])
def getBooks():
    session = DBSession()
    returnedBooks = session.query(BOOK).all()
    session.close()

    return something...

1) 首先,如果我没有明确关闭我的session 对象,它会在处理完request 后自动关闭吗?

2) 当我的应用收到多个请求时,创建的多个session对象是否都链接到创建的单个engine对象在我的 __init__.py 文件中?

3) 在 view.py 中创建的 session 对象是 connection pool 持有的 connections ?如果是这样,并且这些都没有关闭,那么是否必须为后续请求建立新的连接?

4) 我应该在某个时候使用 dispose() 吗?

最佳答案

1) Firstly, if I don't explicitly close my session object, will it automatically close after the request has been processed?

垃圾收集器最终*会在 session 中调用__del__。如果 session 没有被您以其他方式整理出来,这可能会导致回滚。你通常应该做这样的事情:

import contextlib
def myRequestHandler(args):
    with contextlib.closing(DBSession()) as session:
        result = do_stuff(session)
        if neccesary:
            session.commit() 
        else:
            session.rollback()
        return result

2) When my app receives multiple requests, are the multiple session objects being created all linked to the single engine object that was created in my __init__.py file?

是的,sessionmaker()保留所有 Session 配置。使用您获得的模式,您将为每个请求获得一个新 session ,这是一件好事。

3) Are the session objects being created in view.py the connections that the connection pool holds?

sessions and connections不是一回事;尽管每个 session 一次都使用一个连接,并且当他们使用完它们时,它们会将连接返回到池中。

If so, and these weren't closed, then would new connections have to be made for subsequent requests?

different pool implementations有不同的规则,但对于大多数数据库引擎,默认值为 QueuePool ;它的默认最大连接数为 15。对额外连接的后续请求将被阻止或超时。不过,尽可能重用连接。

4) Should I be using dispose() at some point?

通常不需要,如果您还使用池、引擎和 session ,那么可能不需要提交/回滚 session 之外的任何额外资源管理

*eventually 实际上意味着介于立即和从不之间的某个时间;不要指望它做有用的工作;请注意,当您的进程终止时,您的连接将被操作系统强制关闭,因此使用 GC 进行连接管理不会给您带来任何好处。

关于python - SQLAlchemy 连接池和 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29224472/

相关文章:

使用类点的 Python Sierpinski 三角形

python - Azure函数应用程序-输出CosmosDB

android - 处理与 Android/IOS/移动云应用程序的 PHP session

java - 使用用户名和密码发送 POST 请求并保存 session cookie

python - 如何使用 flask 和 sqlalchemy 进行选择查询?

python - flask 迁移 : Alembic converting choices into 255

python - Pyparsing 在上下文中运行

python - 如何向多索引 Pandas 数据帧添加新行和新列?

php - 根据 "major"操作将数据存储到 session 中并存储到数据库中

python - flask-login:Exception: 没有为此 LoginManager 安装 user_loader。用 'LoginManager.user_loader' 装饰器添加一个