async-sqlalchemy-adapter

Asynchronous SQLAlchemy Adapter is the SQLAlchemy adapter for PyCasbin. With this library, Casbin can load policy from SQLAlchemy supported database or save policy to it.
Based on Officially Supported Databases, The current supported databases are:
- PostgreSQL
- MySQL
- MariaDB
- SQLite
- Oracle
- Microsoft SQL Server
- Firebird
Installation
pip install casbin_async_sqlalchemy_adapter
Simple Example
import casbin_async_sqlalchemy_adapter
import casbin
adapter = casbin_async_sqlalchemy_adapter.Adapter('sqlite+aiosqlite:///test.db')
e = casbin.AsyncEnforcer('path/to/model.conf', adapter)
sub = "alice"
obj = "data1"
act = "read"
if e.enforce(sub, obj, act):
pass
else:
pass
Note that AsyncAdaper must be used for AynscEnforcer.
External Session Support
The adapter supports using externally managed SQLAlchemy sessions. This feature is useful for:
- Better transaction control in complex scenarios
- Reducing database connections and communications
- Supporting advanced database features like two-phase commits
- Integrating with existing database session management
Basic Usage with External Session
import casbin_async_sqlalchemy_adapter
import casbin
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
engine = create_async_engine('sqlite+aiosqlite:///test.db')
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
session = async_session()
adapter = casbin_async_sqlalchemy_adapter.Adapter(
'sqlite+aiosqlite:///test.db',
db_session=session
)
e = casbin.AsyncEnforcer('path/to/model.conf', adapter)
Transaction Control Example
async with async_session() as session:
adapter = casbin_async_sqlalchemy_adapter.Adapter(
'sqlite+aiosqlite:///test.db',
db_session=session
)
e = casbin.AsyncEnforcer('path/to/model.conf', adapter)
await e.add_policy("alice", "data1", "read")
await e.add_policy("bob", "data2", "write")
await session.commit()
Batch Operations Example
async with async_session() as session:
adapter = casbin_async_sqlalchemy_adapter.Adapter(
'sqlite+aiosqlite:///test.db',
db_session=session
)
e = casbin.AsyncEnforcer('path/to/model.conf', adapter)
policies = [
["alice", "data1", "read"],
["bob", "data2", "write"],
["carol", "data3", "read"]
]
await e.add_policies(policies)
await session.commit()
Getting Help
License
This project is licensed under the Apache 2.0 license.