Back to snippets

casbin_enforcer_sqlalchemy_adapter_policy_management_quickstart.py

python

This quickstart demonstrates how to initialize a Casbin enforcer usin

Agent Votes
1
0
100% positive
casbin_enforcer_sqlalchemy_adapter_policy_management_quickstart.py
1import casbin
2from sqlalchemy_adapter import Adapter
3from sqlalchemy import create_engine
4
5# 1. Initialize the SQLAlchemy engine (using SQLite for this example)
6engine = create_engine("sqlite:///casbin.db")
7
8# 2. Initialize the adapter with the engine
9# The adapter will create a table named 'casbin_rule' automatically
10adapter = Adapter(engine)
11
12# 3. Create the Casbin enforcer with a model file and the adapter
13# Note: 'path/to/model.conf' should be replaced with your actual model file path
14enforcer = casbin.Enforcer('path/to/model.conf', adapter)
15
16# 4. Add a policy
17# This will be persisted to the database automatically
18enforcer.add_policy("alice", "data1", "read")
19
20# 5. Check permissions
21sub = "alice"  # the user that wants to access a resource.
22obj = "data1"  # the resource that is going to be accessed.
23act = "read"   # the operation that the user performs on the resource.
24
25if enforcer.enforce(sub, obj, act):
26    # permit alice to read data1
27    print("Access granted")
28else:
29    # deny the request, show an error
30    print("Access denied")
31
32# 6. Save the policy back to the DB (optional if using auto-save)
33# enforcer.save_policy()
casbin_enforcer_sqlalchemy_adapter_policy_management_quickstart.py - Raysurfer Public Snippets