Remove sys.path manipulation from example
High-performance Python bindings for casbin-cpp, providing blazing-fast authorization enforcement powered by C++.
pycasbin-on-cpp wraps the casbin-cpp library to provide a Python interface with significantly better performance compared to the pure Python implementation. It maintains API compatibility with pycasbin while leveraging the speed of native C++ code.
# Clone the repository with submodules git clone --recursive https://github.com/casbin/pycasbin-on-cpp.git cd pycasbin-on-cpp # Install dependencies and build pip install -e .
If you already cloned without --recursive:
git submodule update --init --recursive pip install -e .
from pycasbin_cpp import Enforcer # Initialize the enforcer with a model file and a policy file e = Enforcer('path/to/model.conf', 'path/to/policy.csv') # Check permissions if e.enforce(['alice', 'data1', 'read']): print("Permission granted") else: print("Permission denied") # Add a policy e.add_policy(['bob', 'data2', 'write']) # Get all roles for a user roles = e.get_roles_for_user('alice') print(f"Alice's roles: {roles}") # Save policies e.save_policy()
See the examples/ directory for more detailed examples:
# Run the basic example python examples/basic_example.py
The main class for authorization enforcement.
# Create enforcer with model and policy file e = Enforcer(model_path, policy_path) # Create enforcer with only model file e = Enforcer(model_path)
enforce(params): Check if a request is allowedenforce_ex(params): Check permission and get explanationget_policy(): Get all policiesadd_policy(params): Add a policy ruleremove_policy(params): Remove a policy ruleupdate_policy(old_policy, new_policy): Update a policy ruleget_roles_for_user(user): Get roles for a userget_users_for_role(role): Get users for a roleadd_role_for_user(user, role): Add a role for a userdelete_role_for_user(user, role): Delete a role for a userhas_role_for_user(user, role): Check if user has roleget_all_subjects(): Get all subjectsget_all_objects(): Get all objectsget_all_actions(): Get all actionsget_all_roles(): Get all rolespycasbin-on-cpp uses the same model configuration as pycasbin. Here's an example RBAC model:
[request_definition] r = sub, obj, act [policy_definition] p = sub, obj, act [role_definition] g = _, _ [policy_effect] e = some(where (p.eft == allow)) [matchers] m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
pycasbin-on-cpp provides significant performance improvements over pure Python implementations:
# Install development dependencies pip install pybind11 setuptools wheel # Build in development mode python setup.py develop
# Install test dependencies pip install pytest # Run tests pytest tests/
We welcome contributions! Please see CONTRIBUTING.md for details.
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.