본문 바로가기
MySql

MySQL sqlalchemy 세션에서 개체 새로 고침 정보

by 베이스 공부 2020. 12. 22.
반응형

글쎄, 나는 sqlalchemy와 객체 새로 고침에 대한 의구심을 다루고 있습니다!

2 개의 세션이있는 상황에 있고 두 세션 모두에서 동일한 개체가 쿼리되었습니다! ... 어떤 특정 항목에 대해 세션 중 하나를 닫을 수 없습니다. 개체를 수정하고 세션 A에서 변경 사항을 커밋했지만 세션 B에서는 속성이 초기 속성입니다! 수정없이! ..

그래서 ... 변경 사항을 전달하기 위해 일종의 알림 시스템을 구현해야합니까? 아니면 sqlalchemy에서 이것을 수행하는 기본 제공 방법이 있습니까 ??

 

해결 방법

 



세션은 일반적으로 논리의 시작 부분에 구성됩니다. 데이터베이스 액세스가 잠재적으로 예상되는 작업.

세션은 데이터베이스와 통신하는 데 사용될 때마다 database transaction as soon as it starts communicating. Assuming the autocommit flag is left at its recommended default of False, this transaction remains in progress until the Session is rolled back, committed, or closed. The Session will begin a new transaction if it is used again, subsequent to the previous transaction ending; from this it follows that the Session is capable of having a lifespan across many transactions, though only one at a time. We refer to these 트랜잭션 범위와 세션 범위라는 두 가지 개념.

여기서 의미는 SQLAlchemy ORM이 developer to establish these two scopes in his or her application, including not only when the scopes begin and end, but also the expanse of those scopes, for example should a single Session instance be local to the execution flow within a function or method, should it be a global object used by the entire application, or somewhere in between 이 둘.

이 범위를 결정하는 개발자의 부담은 하나의 영역입니다. where the SQLAlchemy ORM necessarily has a strong opinion about how the database should be used. The unit of work pattern is specifically one of accumulating changes over time and flushing them periodically, keeping in-memory state in sync with what’s known to be present in a local transaction. This pattern is only effective when meaningful 트랜잭션 범위가 있습니다.

즉, 상황이 작동하는 방식을 변경하기 위해 수행 할 수있는 몇 가지 작업이 있습니다.

첫째, 세션이 열려있는 시간을 줄일 수 있습니다. 세션 B는 개체를 쿼리 한 다음 나중에 속성을 최신 상태로 유지하려는 해당 개체 (동일한 세션)로 작업을 수행합니다. 한 가지 해결책은이 두 번째 작업을 별도의 세션에서 수행하는 것입니다.


# immediately re-load attributes on obj1, obj2
session.refresh(obj1)
session.refresh(obj2)

# expire objects obj1, obj2, attributes will be reloaded
# on the next access:
session.expire(obj1)
session.expire(obj2)

session.refresh () 를 사용하여 세션이 이미 이전에 객체를 쿼리 한 경우에도 객체의 최신 버전을 즉시 가져올 수 있습니다.

 

참조 페이지 https://stackoverflow.com/questions/19143345

 

 

반응형

댓글