2017-04-02 7 views
1

특정 테이블에서 삽입이 발생한 후 일부 작업을 수행하려고합니다. SAWarning : 'Session.add()'연산의 사용은 현재 실행 단계에서 지원되지 않습니다.

user = ModelFactory.create_user(username, email, password) 
db.session.add(user) 
db.session.commit() 

그래서 나는 after_insert에 자동으로 호출하는 방법을 만들었습니다.

SAWarning: Usage of the 'Session.add()' operation is not currently supported within the execution stage of the flush process. Results may not be consistent. Consider using alternative event listeners or connection-level operations instead. 
    % method) 

/home/avinash/.virtualenvs/s2s/local/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py:68: SAWarning: An exception has occurred during handling of a previous exception. The previous exception is: 
<class 'sqlalchemy.exc.ResourceClosedError'> This transaction is closed 

This

def notify_user(user): 
    print user.id 
    book = Book(author=user.id, name='foo') 
    db.session.add(book) 
    db.session.commit(book) 

@event.listens_for(User, 'after_insert') 
def receive_after_insert(mapper, connection, target): 
    print target 
    notify_user(target) 

그러나이 코드는 경고 등의 표시는, 우리가 before_flush에서 작업을 할 필요가 있음을 보여준다. before_flush 메서드 내에서 로직을 이동하려고 시도했지만 user.id가 None임을 보여줍니다. 예, 엔티티가 db에 커밋되지 않기 때문에 예상됩니다.

마찬가지로 나는 after_flush 이벤트를 시도했지만 여전히 동일한 경고를 표시합니다.

답변

1

after_flush 이벤트는 수행 업무 :

@event.listens_for(User, "after_insert") 
def receive_after_insert(mapper, connection, user): 
    print(user.id) 
    @event.listens_for(Session, "after_flush", once=True) 
    def receive_after_flush(session, context): 
     session.add(Book(author=user.id, name="foo")) 

그런데 왜 대신 User.author에게 관계를 만들고 싶어하지 않을까요?

+0

알림 사용자 메소드의 시작 부분에 db.session.flush()가 추가되었습니다. –

+0

@AvinashRaj 가장 가능성이있는 ORM을 사용하지 않는 것 같습니다. ORM의 주요 기능은 개체를 삽입하여 외래 키를 채울 수있는 순서를 파악할 수 있도록하는 것입니다. – univerio

+0

'db.session'을'Session'으로 사용 하시겠습니까? –