连接上的SQLAlchemy(python)

时间:2013-06-13 17:25:00

标签: python sql sqlalchemy

我理解使用标准MySQLdb驱动程序,您通常使用with语句来确保使用__exit__关闭连接。

SQLAlchemy withsessions是否需要等效的engine语句?或者是关闭连接足够SQLAlchemy的手动超时?

2 个答案:

答案 0 :(得分:1)

以下是文档引用:

  

大多数Web框架都包含用于建立单一的基础架构   与请求关联的会话,正确构建   并在请求结束时拆除相应的拆除。这样   基础设施部分包括Flask-SQLAlchemy等产品   与Flask Web框架结合使用,以及   Zope-SQLAlchemy,与Pyramid和Zope一起使用   构架。 SQLAlchemy强烈建议使用这些产品   可用。

     

在没有集成库的情况下,   SQLAlchemy包含自己的“helper”类,称为scoped_session。

所以,看起来像scoped_session就是你在说什么。关于如何使用范围会话的Documentation非常好。基本上,您可以定义何时打开会话以及何时关闭它(请参阅Using Custom Created Scopes):

from my_web_framework import get_current_request, on_request_end
from sqlalchemy.orm import scoped_session, sessionmaker

Session = scoped_session(sessionmaker(bind=some_engine), scopefunc=get_current_request)

@on_request_end
def remove_session(req):
    Session.remove()

希望有所帮助。

答案 1 :(得分:1)

您要查找的短语是“context manager”,它是一个符合with语句中需要使用的属性命名约定的对象。有关使用引擎连接的上下文管理器的文档,请参阅文档中的"Working with the Engine"

with engine.begin() as connection:
    r1 = connection.execute(table1.select())
    connection.execute(table1.insert(), col1=7, col2='this is some data')

据我所知,Session对象本身没有这样的功能。