Skip to content

Commit e580bab

Browse files
authored
feat: Support reusing existing MongoDB client instances (#10)
1 parent 6dbea4f commit e580bab

File tree

3 files changed

+97
-12
lines changed

3 files changed

+97
-12
lines changed

README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,24 @@ filter.raw_query = {
5959
e.load_filtered_policy(filter)
6060
```
6161

62+
## Using an Existing MongoDB Client
63+
64+
If you already have a MongoDB client instance in your application, you can reuse it:
65+
66+
```python
67+
from pymongo import MongoClient
68+
import casbin_pymongo_adapter
69+
import casbin
70+
71+
# Create or use your existing MongoDB client
72+
mongo_client = MongoClient('mongodb://localhost:27017/')
73+
74+
# Pass the client to the adapter
75+
adapter = casbin_pymongo_adapter.Adapter(client=mongo_client, db_name="casbin")
76+
77+
e = casbin.Enforcer('path/to/model.conf', adapter, True)
78+
```
79+
6280
## Async Example
6381

6482
```python
@@ -73,6 +91,23 @@ e = casbin.AsyncEnforcer('path/to/model.conf', adapter)
7391
await e.load_policy()
7492
```
7593

94+
### Using an Existing AsyncMongoClient
95+
96+
```python
97+
from pymongo import AsyncMongoClient
98+
from casbin_pymongo_adapter.asynchronous import Adapter
99+
import casbin
100+
101+
# Create or use your existing AsyncMongoClient
102+
mongo_client = AsyncMongoClient('mongodb://localhost:27017/')
103+
104+
# Pass the client to the adapter
105+
adapter = Adapter(client=mongo_client, db_name="casbin")
106+
e = casbin.AsyncEnforcer('path/to/model.conf', adapter)
107+
108+
await e.load_policy()
109+
```
110+
76111

77112
### Getting Help
78113

casbin_pymongo_adapter/adapter.py

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,47 @@ class Adapter(persist.Adapter):
99

1010
def __init__(
1111
self,
12-
uri,
13-
dbname,
12+
uri=None,
13+
dbname=None,
1414
collection="casbin_rule",
1515
filtered=False,
16+
client=None,
17+
db_name=None,
1618
):
1719
"""Create an adapter for Mongodb
1820
1921
Args:
20-
uri (str): This should be the same requiement as pymongo Client's 'uri' parameter.
22+
uri (str, optional): This should be the same requiement as pymongo Client's 'uri' parameter.
2123
See https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient.
22-
dbname (str): Database to store policy.
24+
Required if client is not provided.
25+
dbname (str, optional): Database to store policy. Required if client is not provided.
2326
collection (str, optional): Collection of the choosen database. Defaults to "casbin_rule".
2427
filtered (bool, optional): Whether to use filtered query. Defaults to False.
28+
client (MongoClient, optional): An existing MongoClient instance to reuse. If provided, uri is ignored.
29+
db_name (str, optional): Database name to use with the provided client. Takes precedence over dbname.
30+
31+
Note:
32+
When both client and uri are provided, client takes precedence and uri is ignored.
2533
"""
26-
client = MongoClient(uri)
27-
db = client[dbname]
34+
# Support both db_name and dbname for backward compatibility
35+
database_name = db_name if db_name is not None else dbname
36+
37+
if client is not None:
38+
# Use the provided client
39+
if database_name is None:
40+
raise ValueError(
41+
"db_name or dbname must be provided when using an existing client"
42+
)
43+
mongo_client = client
44+
else:
45+
# Create a new client from URI
46+
if uri is None:
47+
raise ValueError("uri must be provided when client is not specified")
48+
if database_name is None:
49+
raise ValueError("dbname must be provided when client is not specified")
50+
mongo_client = MongoClient(uri)
51+
52+
db = mongo_client[database_name]
2853
self._collection = db[collection]
2954
self._filtered = filtered
3055

casbin_pymongo_adapter/asynchronous/adapter.py

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,22 +10,47 @@ class Adapter(AsyncAdapter):
1010

1111
def __init__(
1212
self,
13-
uri,
14-
dbname,
13+
uri=None,
14+
dbname=None,
1515
collection="casbin_rule",
1616
filtered=False,
17+
client=None,
18+
db_name=None,
1719
):
1820
"""Create an adapter for Mongodb
1921
2022
Args:
21-
uri (str): This should be the same requiement as pymongo Client's 'uri' parameter.
23+
uri (str, optional): This should be the same requiement as pymongo Client's 'uri' parameter.
2224
See https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient.
23-
dbname (str): Database to store policy.
25+
Required if client is not provided.
26+
dbname (str, optional): Database to store policy. Required if client is not provided.
2427
collection (str, optional): Collection of the choosen database. Defaults to "casbin_rule".
2528
filtered (bool, optional): Whether to use filtered query. Defaults to False.
29+
client (AsyncMongoClient, optional): An existing AsyncMongoClient instance to reuse. If provided, uri is ignored.
30+
db_name (str, optional): Database name to use with the provided client. Takes precedence over dbname.
31+
32+
Note:
33+
When both client and uri are provided, client takes precedence and uri is ignored.
2634
"""
27-
client = AsyncMongoClient(uri)
28-
db = client[dbname]
35+
# Support both db_name and dbname for backward compatibility
36+
database_name = db_name if db_name is not None else dbname
37+
38+
if client is not None:
39+
# Use the provided client
40+
if database_name is None:
41+
raise ValueError(
42+
"db_name or dbname must be provided when using an existing client"
43+
)
44+
mongo_client = client
45+
else:
46+
# Create a new client from URI
47+
if uri is None:
48+
raise ValueError("uri must be provided when client is not specified")
49+
if database_name is None:
50+
raise ValueError("dbname must be provided when client is not specified")
51+
mongo_client = AsyncMongoClient(uri)
52+
53+
db = mongo_client[database_name]
2954
self._collection = db[collection]
3055
self._filtered = filtered
3156

0 commit comments

Comments
 (0)