hsluoyz commented on issue #27: URL: https://github.com/apache/casbin-python-async-sqlalchemy-adapter/issues/27#issuecomment-5205141648
@UnoYakshi Valid point, thanks for the detailed write-up — the constructor's `db_session` only binds a session for the adapter's whole lifetime, which doesn't help when the enforcer is a long-lived singleton. Fixed in [[d8efc20](https://github.com/apache/casbin-python-async-sqlalchemy-adapter/commit/d8efc20b48f9e987387247fd938223f27b7f6080)](https://github.com/apache/casbin-python-async-sqlalchemy-adapter/commit/d8efc20b48f9e987387247fd938223f27b7f6080) with an `adapter.use_session()` context manager: ```python async with db_session.begin(): db_session.add(user) await db_session.flush() async with adapter.use_session(db_session): await enforcer.add_role_for_user(str(user.id), "admin") ``` Inside the block the adapter joins your transaction and never commits or rolls back, so policy changes live or die with your own. I went with a context manager rather than per-method `session=`/`commit=` arguments because those methods are called by the enforcer internally, so there'd be no way to pass a session through `enforcer.add_policy(...)`. The binding lives in a `ContextVar`, so concurrent requests sharing one adapter each keep their own session. Same commit also makes `update_policies()` and `update_filtered_policies()` run in a single transaction instead of one per rule. Note that the enforcer's in-memory policy isn't reverted by a rollback — call `await enforcer.load_policy()` to resync. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
