|
27 | 27 | from typing import Any
|
28 | 28 |
|
29 | 29 | from flask import abort
|
30 |
| -from pymongo import collection |
| 30 | +from pymongo import collection, database, mongo_client |
| 31 | + |
| 32 | + |
| 33 | +class MongoClient(mongo_client.MongoClient[dict[str, Any]]): |
| 34 | + """Wrapper for :class:`~pymongo.mongo_client.MongoClient`. |
| 35 | +
|
| 36 | + Returns instances of Flask-PyMongo |
| 37 | + :class:`~flask_pymongo.wrappers.Database` instead of native PyMongo |
| 38 | + :class:`~pymongo.database.Database` when accessed with dot notation. |
| 39 | +
|
| 40 | + """ |
| 41 | + |
| 42 | + def __getattr__(self, name: str) -> Any: |
| 43 | + attr = super().__getattr__(name) |
| 44 | + if isinstance(attr, database.Database): |
| 45 | + return Database(self, name) |
| 46 | + return attr |
| 47 | + |
| 48 | + def __getitem__(self, name: str) -> Any: |
| 49 | + attr = super().__getitem__(name) |
| 50 | + if isinstance(attr, database.Database): |
| 51 | + return Database(self, name) |
| 52 | + return attr |
| 53 | + |
| 54 | + |
| 55 | +class Database(database.Database[dict[str, Any]]): |
| 56 | + """Wrapper for :class:`~pymongo.database.Database`. |
| 57 | +
|
| 58 | + Returns instances of Flask-PyMongo |
| 59 | + :class:`~flask_pymongo.wrappers.Collection` instead of native PyMongo |
| 60 | + :class:`~pymongo.collection.Collection` when accessed with dot notation. |
| 61 | +
|
| 62 | + """ |
| 63 | + |
| 64 | + def __getattr__(self, name: str) -> Any: |
| 65 | + attr = super().__getattr__(name) |
| 66 | + if isinstance(attr, collection.Collection): |
| 67 | + return Collection(self, name) |
| 68 | + return attr |
| 69 | + |
| 70 | + def __getitem__(self, name: str) -> Any: |
| 71 | + item_ = super().__getitem__(name) |
| 72 | + if isinstance(item_, collection.Collection): |
| 73 | + return Collection(self, name) |
| 74 | + return item_ |
31 | 75 |
|
32 | 76 |
|
33 | 77 | class Collection(collection.Collection[dict[str, Any]]):
|
34 | 78 | """Sub-class of PyMongo :class:`~pymongo.collection.Collection` with helpers."""
|
35 | 79 |
|
| 80 | + def __getattr__(self, name: str) -> Any: |
| 81 | + attr = super().__getattr__(name) |
| 82 | + if isinstance(attr, collection.Collection): |
| 83 | + db = self._Collection__database |
| 84 | + return Collection(db, attr.name) |
| 85 | + return attr |
| 86 | + |
| 87 | + def __getitem__(self, name: str) -> Any: |
| 88 | + item = super().__getitem__(name) |
| 89 | + if isinstance(item, collection.Collection): |
| 90 | + db = self._Collection__database |
| 91 | + return Collection(db, item.name) |
| 92 | + return item |
| 93 | + |
36 | 94 | def find_one_or_404(self, *args: Any, **kwargs: Any) -> Any:
|
37 | 95 | """Find a single document or raise a 404.
|
38 | 96 |
|
|
0 commit comments