Skip to content

Commit 4ed70fd

Browse files
committed
add_function can support both async and sync; add await enforce.enforce()
1 parent a523245 commit 4ed70fd

2 files changed

Lines changed: 13 additions & 0 deletions

File tree

casbin/async_enforcer.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# limitations under the License.
1414

1515
from functools import partial
16+
import asyncio
1617

1718
from casbin.async_management_enforcer import AsyncManagementEnforcer
1819
from casbin.util import join_slice, array_remove_duplicates, set_subtract
@@ -22,6 +23,15 @@ class AsyncEnforcer(AsyncManagementEnforcer):
2223
"""
2324
AsyncEnforcer = AsyncManagementEnforcer + RBAC_API + RBAC_WITH_DOMAIN_API
2425
"""
26+
async def enforce(self, *rvals):
27+
loop = asyncio.get_running_loop()
28+
result = await loop.run_in_executor(None, super().enforce, *rvals)
29+
return result
30+
31+
async def batch_enforce(self, rvals):
32+
"""batch_enforce enforce in batches"""
33+
tasks = [self.enforce(*request) for request in rvals]
34+
return await asyncio.gather(*tasks)
2535

2636
async def get_roles_for_user(self, name):
2737
"""gets the roles that a user has."""

casbin/core_enforcer.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import copy
1616
import logging
1717
import re
18+
import asyncio
1819

1920
from casbin.effect import Effector, get_effector, effect_to_bool
2021
from casbin.model import Model, FunctionMap
@@ -457,6 +458,8 @@ def enforce_ex(self, *rvals):
457458
expression = self._get_expression(exp_with_rule, functions)
458459

459460
result = expression.eval(parameters)
461+
if asyncio.iscoroutine(result):
462+
result = asyncio.run(result)
460463

461464
if isinstance(result, bool):
462465
if not result:

0 commit comments

Comments
 (0)