简体   繁体   English

没有ORM的金字塔和SqlAlchemy.Session的使用

[英]Pyramid and SqlAlchemy without ORM.Use of Session

This is in further extension to this . 这是在进一步扩展这个

I am building project in pyramid using sqlalchemy without its ORM. 我正在使用不带ORM的sqlalchemy在金字塔中构建项目。 I find the session feature to be nice as I wont have to commit everytime a request is over.This is how I am implementing it: 我发现会话功能很好,因为每次请求结束时我都不必提交,这就是我实现它的方式:

from sqlalchemy.orm import (
    scoped_session,
    sessionmaker,
    )

from zope.sqlalchemy import ZopeTransactionExtension

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))

Question :To execute only SQL statement do i need to create a session? 问题 :仅执行SQL语句,我需要创建一个会话吗?

If yes ,how can I execute sqlstatement using DBSession. 如果是 ,如何使用DBSession执行sqlstatement。

If no ,how can I do the same and take care of all the functionality offered by session and zopeTransactionExtension() 如果没有 ,我该怎么做,并注意session和zopeTransactionExtension()提供的所有功能。

Yes, you do need to create a session if you want to use the "commit on success, roll back on failure" behaviour of a session configured with ZopeTransactionExtension. 是的,如果要使用通过ZopeTransactionExtension配置的会话的“成功提交,失败时回滚”行为,则确实需要创建一个会话。

def my_view(request):
    session = DBSession()

    result = session.execute("""SELECT spam, eggs FROM blah WHERE moo='foo'""")
    data = []
    for row in result:
        data.append({
           'spam': row.spam, 
           'eggs': row.eggs
        })
    return data

With SQLAlchemy it is also possible to get access to the underlying "engine" and "connection" used by the session, so you can run queries outside of a transaction block, or using a specific DB connection, but it perhaps only useful in very specific circumstances. 使用SQLAlchemy,还可以访问会话使用的基础“引擎”和“连接”,因此您可以在事务块之外或使用特定的数据库连接来运行查询,但它可能仅在非常特定的情况下有用情况。

I don't think there's any measurable overhead in just using session.execute() everywhere. 我认为仅在各处使用session.execute()并不会带来任何可衡量的开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM