pycasbin / async-sqlalchemy-adapter

Async SQLAlchemy Adapter for PyCasbin
https://github.com/casbin/pycasbin
Apache License 2.0
7 stars 5 forks source link

how to set schema using with postgres database #13

Closed language-cat closed 6 months ago

language-cat commented 6 months ago

this is my code:

pgsql_async_engine = create_async_engine(
    pgsql_url,
    echo=True,
    pool_pre_ping=True,
    pool_size=10,
    max_overflow=20,
    pool_timeout=30,
    pool_recycle=1800,
)

async def get_enforcer(user):
    adapter = Adapter(pgsql_async_engine)
    casbin_enforcer = casbin.AsyncEnforcer(str(Path(__file__).parent.parent.parent / "model.conf"), adapter)
    await casbin_enforcer.load_policy()
    role = await casbin_enforcer.get_roles_for_user(user.username)
    return casbin_enforcer

how to set schema when using create_async_engine

casbin-bot commented 6 months ago

@techoner @Nekotoxin

siuhui commented 6 months ago

@language-cat It seems that the function create_async_engine does not support specifying the ‘schema’ parameter.

siuhui commented 6 months ago

@language-cat hi, you can specify the ‘schema’ in a SQLAlchemy model class.

For example:

Base = declarative_base()

class CasbinRule(Base):
    __tablename__ = "casbin_rule"
    __table_args__ = {'schema': 'your_schema'}

    id = Column(Integer, primary_key=True)
    ptype = Column(String(255))
    v0 = Column(String(255))
    v1 = Column(String(255))
    v2 = Column(String(255))
    v3 = Column(String(255))
    v4 = Column(String(255))
    v5 = Column(String(255))

    def __str__(self):
        arr = [self.ptype]
        for v in (self.v0, self.v1, self.v2, self.v3, self.v4, self.v5):
            if v is None:
                break
            arr.append(v)
        return ", ".join(arr)

    def __repr__(self):
        return '<CasbinRule {}: "{}">'.format(self.id, str(self))

async def get_enforcer():
    engine = create_async_engine(
        "postgresql+asyncpg://user:password@hostname/dbname",
        echo=True,
    )
    adapter = Adapter(engine, db_class=CasbinRule)
    await adapter.create_table()
    e = casbin.AsyncEnforcer("rbac_model.conf", adapter)
    await e.load_policy()
    return e
hsluoyz commented 6 months ago

Closed as resolved