金字塔事务管理器不承诺更新

时间:2014-08-12 13:25:16

标签: python postgresql sqlalchemy pyramid

对不起我以前不清楚,

编辑: 我正在使用sqlalchemy(backend:postgresql)的默认金字塔应用程序,使用

生成
pcreate -s alchemy

所以我有与DBSession,pyramid_tm等相关的所有设置。我有这个代码

class User(Base):
    id = Column(Integer, primary_key=True)
    connection = relationship("UserConnection", uselist=False, backref="user")

class UserConnection(Base):
    userid = Column(Integer, ForeignKey('user.id'), primary_key=True)
    friends = Column(JSON)

def add_connection(user, friend):
    with transaction.manager:
        if not user.connection:
            user_conn = UserConnection(userid=user.id, friends=[])
        else:
            user_conn = user.connection

        user_conn.friends.append(friend)
        print(user_connection.friends)
        session.add(user_conn)

当我第一次运行add_connection()时,user.connection不在那里。新记录被创建但在下次运行时(如果这转到其他地方)记录没有得到更新,在控制台上我只能看到ROLLBACK / COMMIT但没有其他语句。

那里的print语句显示更新的结果,但db没有更新。

1 个答案:

答案 0 :(得分:3)

您应该在请求范围内使用事务。

zope.sqlalchemy和pyramid_tm可以为您做到这一点。 您可以使用我的代码:

pyramid_sqlalchemy.py

# -*- coding: utf-8 -*-

""" Pyramid sqlalchemy lib.

Session will be available as dbsession attribute on request.

! Do not close session on your own.

"""

import sqlalchemy
from sqlalchemy.orm import sessionmaker, scoped_session
from zope.sqlalchemy import ZopeTransactionExtension

Session = scoped_session(sessionmaker(
    extension=ZopeTransactionExtension()
))


def includeme(config):
    """ Setup sqlalchemy session connection for pyramid app.

    :param config: Pyramid configuration

    """
    config.include('pyramid_tm')
    # creates database engine from ini settings passed to pyramid wsgi
    engine = sqlalchemy.engine_from_config(
        config.get_settings(), connect_args={
            'charset': 'utf8'
        }
    )
    # scoped session gives us thread safe session
    Session.configure(bind=engine)
    # make database session available in every request
    config.add_request_method(
        callable=lambda request: Session, name='dbsession', property=True
    )

使用pip安装zope.sqlalchemy和pyramid_tm并调用config.include(pyramid_sqlalchemy)