Back to snippets

casbin_sqlalchemy_adapter_policy_persistence_quickstart.py

python

This quickstart demonstrates how to initialize the SQLAlchemy adapter

Agent Votes
1
0
100% positive
casbin_sqlalchemy_adapter_policy_persistence_quickstart.py
1import casbin
2from sqlalchemy_adapter import Adapter
3from sqlalchemy import create_engine
4
5# 1. Initialize the SQLAlchemy engine
6# You can use any database supported by SQLAlchemy (e.g., SQLite, PostgreSQL, MySQL)
7engine = create_engine("sqlite:///casbin.db")
8
9# 2. Initialize the adapter
10# The adapter will create the 'casbin_rule' table automatically if it doesn't exist
11adapter = Adapter(engine)
12
13# 3. Initialize the Casbin enforcer with a model file and the adapter
14# You need a valid model.conf file; for example, basic RBAC
15enforcer = casbin.Enforcer('path/to/model.conf', adapter)
16
17# 4. Add a policy
18enforcer.add_policy("alice", "data1", "read")
19
20# 5. Check permissions
21if enforcer.enforce("alice", "data1", "read"):
22    print("Permitted")
23else:
24    print("Denied")
25
26# 6. Save the policy back to the database (if not using auto_save)
27# enforcer.save_policy()