idwaker
idwaker

Reputation: 416

pyramid transaction manager not committing on update

Sorry i wasn't clear before,

Edited: I am using default pyramid application with sqlalchemy (backend: postgresql), generated using

pcreate -s alchemy

So i have all the settings related to DBSession, pyramid_tm etc. I have this code

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)

when i run add_connection() first time that is user.connection is not there. New record gets created but on next run ( in case this goes to else ) record don't get updated, on console i can only see ROLLBACK/COMMIT but no other statements.

The print statement there shows the updated result but db is not updated.

Upvotes: 2

Views: 1602

Answers (1)

Rafał Łużyński
Rafał Łużyński

Reputation: 7312

You should use transaction in request scope.

zope.sqlalchemy and pyramid_tm can do that for you. You can use my code:

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
    )

Install zope.sqlalchemy and pyramid_tm using pip and call config.include(pyramid_sqlalchemy)

Upvotes: 3

Related Questions