# kover






**Kover** is a model-orientied strict typed mongodb driver supporting local mongod and replica sets. Battle tests are still required*<br>
this library was inspired by <a href=https://github.com/sakal/aiomongo>this project</a> i like it very much. Though its 8 years old.
Kover is linted by Ruff and supports pyright strict type checking mode.
```py
import asyncio
from kover import AuthCredentials, Kover
async def main():
# or AuthCredentials.from_environ()
# (requires MONGO_USER and MONGO_PASSWORD environment variables)
# (remove if no auth present)
credentials = AuthCredentials(username="...", password="...")
client = await Kover.make_client(credentials=credentials)
found = await client.db.test.find().limit(10).to_list()
print(found)
if __name__ == "__main__":
asyncio.run(main())
```
The main reason why i created this project is that Motor - official async wrapper for mongodb, uses ThreadPool executor and it's just a wrapper around pymongo. In general thats slower than clear asyncio and looks more dirty.
- 02.12.24 UPDATE: pymongo added async support but its kinda messed up and not clear. pymongo's code looks dirty and have lots of unnecessary things. kover almost 1.5-2 times faster than pymongo.
# Status
it still missing features. <br>
e.g: **bulk write API** and **Compression**<br>
but its already very cool! <br>
# Dependencies
- All platforms.
- python 3.10
- MongoDB 6.0+ (not sure about older versions)
- pydantic 2.10.6 or later
# Features
Almost all features from pymongo. All auth types are supported. Integration with Pydantic supported.
this lib was built for new mongod versions. All features that were marked as DEPRECATED in docs
were NOT added. See docs for references. The kover.bson package was entirely copied from pymongo source code. Also pymongo.saslprep was copied for internal purposes, i do not own these files.
### Cursors
if you just need list:
```py
items = await db.test.find().limit(1000).batch_size(50).to_list()
```
### or
```py
async with db.test.find().limit(1000).batch_size(50) as cursor:
async for item in cursor:
print(item)
```
### if collection has specific schema:
```py
from kover import Document
class User(Document):
uuid: UUID
name: str
age: int
async with db.test.find(cls=User).limit(1000) as cursor:
async for item in cursor:
print(item) # its now User
```
### Schema Validation
some people say that mongodb is dirty because you can insert any document in collection. Kover fixes that! Use `pydantic.Field` here if you need
Document is a Pydantic Model in 2.0
```py
import asyncio
from enum import Enum
import logging
from typing import Annotated
from pydantic import ValidationError
from kover import (
AuthCredentials,
Document,
Kover,
OperationFailure,
SchemaGenerator,
)
from kover.metadata import SchemaMetadata
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
class UserType(Enum): # noqa: D101
ADMIN = "ADMIN"
USER = "USER"
CREATOR = "CREATOR"
class Friend(Document): # noqa: D101
name: str
age: Annotated[int, SchemaMetadata(minimum=18)] # minimum age is 18.
# kover automatically generates aliases using camel case.
# so user_type will be "userType" in db
# if you still need to snake cased field_name
# use explicit alias="<snake_cased_name>"
class User(Document): # noqa: D101
name: Annotated[str, SchemaMetadata(description="must be a string")]
age: Annotated[
int,
SchemaMetadata(
description="age must be int and more that 18", minimum=18,
),
]
user_type: Annotated[
UserType,
SchemaMetadata(description="can only be one of the enum values"),
]
friend: Friend | None
async def main() -> None: # noqa: D103
credentials = AuthCredentials.from_environ()
client = await Kover.make_client(credentials=credentials)
generator = SchemaGenerator()
schema = generator.generate(User)
collection = await client.db.test.create_if_not_exists()
await collection.set_validator(schema)
valid_user = User(
name="John Doe",
age=20,
user_type=UserType.USER,
friend=Friend(name="dima", age=18),
)
# function accepts either valid_user or valid_user.to_dict()
object_id = await collection.insert(valid_user)
log.info(f"{object_id}, added!")
try:
invalid_user = User(
name="Rick",
age=15,
user_type=UserType.ADMIN,
friend=Friend(name="roma", age=25),
)
except ValidationError as e: # it wont let you create such model
raise SystemExit(e.errors()) from e
# somehow if you try to insert invalid_user.to_dict()
# kover.exceptions.ErrDocumentValidationFailure: Rick's age is less than 18
try:
await collection.insert(invalid_user)
except OperationFailure as e:
msg: str = e.message["errmsg"]
log.info(f"got Error: {msg}")
assert e.code == 121 # ErrDocumentValidationFailure # noqa: E501, PT017
if __name__ == "__main__":
asyncio.run(main())
```
### Transactions
```py
import asyncio
import logging
from typing import TYPE_CHECKING
from kover.bson import ObjectId
from kover import AuthCredentials, Kover
if TYPE_CHECKING:
from kover import xJsonT
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
async def main() -> None: # noqa: D103
credentials = AuthCredentials.from_environ()
client = await Kover.make_client(credentials=credentials)
session = await client.start_session()
# specify _id directly
doc: xJsonT = {"_id": ObjectId(), "name": "John", "age": 30}
collection = await client.db.test.create_if_not_exists()
async with session.start_transaction() as transaction:
await collection.insert(doc, transaction=transaction)
# it should error with duplicate key now
await collection.insert(doc, transaction=transaction)
exc = transaction.exception # if exist
log.info(f"{exc}, {type(exc)}")
log.info(f"trx state: {transaction.state}")
found = await collection.find().to_list()
log.info(found) # no documents found due to transaction abort
if __name__ == "__main__":
asyncio.run(main())
```
### GridFS
```py
import asyncio
import logging
from kover import AuthCredentials, Kover
from kover.gridfs import GridFS
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
async def main() -> None: # noqa: D103
credentials = AuthCredentials.from_environ()
client = await Kover.make_client(credentials=credentials)
database = client.get_database("files")
fs = await GridFS(database).indexed()
# can be bytes, any type of IO str or path
file_id = await fs.put(b"Hello World!")
file, binary = await fs.get_by_file_id(file_id)
log.info(file, binary.read())
files = await fs.list()
log.info(f"total files: {len(files)}")
deleted = await fs.delete(file_id)
log.info(f"is file deleted? {deleted}")
if __name__ == "__main__":
asyncio.run(main())
```
### Updating/Deleting docs
```py
import asyncio
import logging
from typing import TYPE_CHECKING
from kover import (
AuthCredentials,
Delete,
Document,
Kover,
Update,
)
if TYPE_CHECKING:
from kover.bson import ObjectId
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
class User(Document): # noqa: D101
name: str
age: int
async def main() -> None: # noqa: D103
credentials = AuthCredentials.from_environ()
kover = await Kover.make_client(credentials=credentials)
collection = kover.db.get_collection("test")
user = User(name="John", age=23)
file_id: ObjectId = await collection.insert(user) # or user.to_dict()
# this concept requires using "$set" explicitly
# if you dont specify it your entire doc will be
# just replaced fully to specified here
# advancements of this way is that you can do anything here not only "$set"
# e.g {"$push": {"userIds": 12345}} and more
# in conclusion: be careful with specifying "$set", dont forget it!
update = Update({"_id": file_id}, {"$set": {"name": "Wick"}})
await collection.update(update)
# limit 1 corresponds to .delete_one and 0 to .delete_many
delete = Delete({"_id": file_id}, limit=1)
n = await collection.delete(delete)
log.info(f"documents deleted: {n}") # 1
if __name__ == "__main__":
asyncio.run(main())
```
# If you found a bug, go ahead and open an issue, or even better a pull request, thx ❤️
Raw data
{
"_id": null,
"home_page": null,
"name": "kover",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.10",
"maintainer_email": null,
"keywords": "Kover API mongo, Mongo Kover, async driver, kover, kover mongodb, megawattka, mongo async, mongo kover, mongod driver, mongodb",
"author": null,
"author_email": "megawattka <gunter56741@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/09/bd/70f3b1eeb998beeed88c4d6df5c76dbbf525155b748de71363a83253aa86/kover-2.3.0.tar.gz",
"platform": null,
"description": "# kover\n\n\n\n\n\n\n\n\n**Kover** is a model-orientied strict typed mongodb driver supporting local mongod and replica sets. Battle tests are still required*<br>\nthis library was inspired by <a href=https://github.com/sakal/aiomongo>this project</a> i like it very much. Though its 8 years old.\nKover is linted by Ruff and supports pyright strict type checking mode.\n\n```py\nimport asyncio\n\nfrom kover import AuthCredentials, Kover\n\n\nasync def main():\n # or AuthCredentials.from_environ()\n # (requires MONGO_USER and MONGO_PASSWORD environment variables)\n # (remove if no auth present)\n credentials = AuthCredentials(username=\"...\", password=\"...\")\n client = await Kover.make_client(credentials=credentials)\n\n found = await client.db.test.find().limit(10).to_list()\n print(found)\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n```\n\nThe main reason why i created this project is that Motor - official async wrapper for mongodb, uses ThreadPool executor and it's just a wrapper around pymongo. In general thats slower than clear asyncio and looks more dirty.\n- 02.12.24 UPDATE: pymongo added async support but its kinda messed up and not clear. pymongo's code looks dirty and have lots of unnecessary things. kover almost 1.5-2 times faster than pymongo.\n\n# Status\nit still missing features. <br>\ne.g: **bulk write API** and **Compression**<br>\nbut its already very cool! <br>\n\n# Dependencies\n- All platforms.\n- python 3.10\n- MongoDB 6.0+ (not sure about older versions)\n- pydantic 2.10.6 or later\n\n# Features\nAlmost all features from pymongo. All auth types are supported. Integration with Pydantic supported.\nthis lib was built for new mongod versions. All features that were marked as DEPRECATED in docs\nwere NOT added. See docs for references. The kover.bson package was entirely copied from pymongo source code. Also pymongo.saslprep was copied for internal purposes, i do not own these files.\n\n### Cursors\nif you just need list:\n\n```py\nitems = await db.test.find().limit(1000).batch_size(50).to_list()\n```\n\n### or\n```py\nasync with db.test.find().limit(1000).batch_size(50) as cursor:\n async for item in cursor:\n print(item)\n```\n### if collection has specific schema:\n```py\nfrom kover import Document\n\nclass User(Document):\n uuid: UUID\n name: str\n age: int\n\n\nasync with db.test.find(cls=User).limit(1000) as cursor:\n async for item in cursor:\n print(item) # its now User\n\n```\n\n### Schema Validation\nsome people say that mongodb is dirty because you can insert any document in collection. Kover fixes that! Use `pydantic.Field` here if you need\nDocument is a Pydantic Model in 2.0\n```py\nimport asyncio\nfrom enum import Enum\nimport logging\nfrom typing import Annotated\n\nfrom pydantic import ValidationError\n\nfrom kover import (\n AuthCredentials,\n Document,\n Kover,\n OperationFailure,\n SchemaGenerator,\n)\nfrom kover.metadata import SchemaMetadata\n\nlog = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO)\n\n\nclass UserType(Enum): # noqa: D101\n ADMIN = \"ADMIN\"\n USER = \"USER\"\n CREATOR = \"CREATOR\"\n\n\nclass Friend(Document): # noqa: D101\n name: str\n age: Annotated[int, SchemaMetadata(minimum=18)] # minimum age is 18.\n\n\n# kover automatically generates aliases using camel case.\n# so user_type will be \"userType\" in db\n# if you still need to snake cased field_name\n# use explicit alias=\"<snake_cased_name>\"\nclass User(Document): # noqa: D101\n name: Annotated[str, SchemaMetadata(description=\"must be a string\")]\n age: Annotated[\n int,\n SchemaMetadata(\n description=\"age must be int and more that 18\", minimum=18,\n ),\n ]\n user_type: Annotated[\n UserType,\n SchemaMetadata(description=\"can only be one of the enum values\"),\n ]\n friend: Friend | None\n\n\nasync def main() -> None: # noqa: D103\n credentials = AuthCredentials.from_environ()\n client = await Kover.make_client(credentials=credentials)\n\n generator = SchemaGenerator()\n schema = generator.generate(User)\n\n collection = await client.db.test.create_if_not_exists()\n await collection.set_validator(schema)\n\n valid_user = User(\n name=\"John Doe\",\n age=20,\n user_type=UserType.USER,\n friend=Friend(name=\"dima\", age=18),\n )\n # function accepts either valid_user or valid_user.to_dict()\n object_id = await collection.insert(valid_user)\n log.info(f\"{object_id}, added!\")\n\n try:\n invalid_user = User(\n name=\"Rick\",\n age=15,\n user_type=UserType.ADMIN,\n friend=Friend(name=\"roma\", age=25),\n )\n except ValidationError as e: # it wont let you create such model\n raise SystemExit(e.errors()) from e\n\n # somehow if you try to insert invalid_user.to_dict()\n # kover.exceptions.ErrDocumentValidationFailure: Rick's age is less than 18\n try:\n await collection.insert(invalid_user)\n except OperationFailure as e:\n msg: str = e.message[\"errmsg\"]\n log.info(f\"got Error: {msg}\")\n assert e.code == 121 # ErrDocumentValidationFailure # noqa: E501, PT017\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n\n```\n\n### Transactions\n\n```py\nimport asyncio\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom kover.bson import ObjectId\n\nfrom kover import AuthCredentials, Kover\n\nif TYPE_CHECKING:\n from kover import xJsonT\n\nlog = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO)\n\n\nasync def main() -> None: # noqa: D103\n credentials = AuthCredentials.from_environ()\n client = await Kover.make_client(credentials=credentials)\n session = await client.start_session()\n\n # specify _id directly\n doc: xJsonT = {\"_id\": ObjectId(), \"name\": \"John\", \"age\": 30}\n collection = await client.db.test.create_if_not_exists()\n\n async with session.start_transaction() as transaction:\n await collection.insert(doc, transaction=transaction)\n # it should error with duplicate key now\n await collection.insert(doc, transaction=transaction)\n\n exc = transaction.exception # if exist\n log.info(f\"{exc}, {type(exc)}\")\n log.info(f\"trx state: {transaction.state}\")\n\n found = await collection.find().to_list()\n log.info(found) # no documents found due to transaction abort\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n\n```\n\n### GridFS\n\n```py\nimport asyncio\nimport logging\n\nfrom kover import AuthCredentials, Kover\nfrom kover.gridfs import GridFS\n\nlog = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO)\n\n\nasync def main() -> None: # noqa: D103\n credentials = AuthCredentials.from_environ()\n client = await Kover.make_client(credentials=credentials)\n\n database = client.get_database(\"files\")\n fs = await GridFS(database).indexed()\n\n # can be bytes, any type of IO str or path\n file_id = await fs.put(b\"Hello World!\")\n\n file, binary = await fs.get_by_file_id(file_id)\n log.info(file, binary.read())\n\n files = await fs.list()\n log.info(f\"total files: {len(files)}\")\n\n deleted = await fs.delete(file_id)\n log.info(f\"is file deleted? {deleted}\")\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n\n```\n\n### Updating/Deleting docs\n\n```py\nimport asyncio\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom kover import (\n AuthCredentials,\n Delete,\n Document,\n Kover,\n Update,\n)\n\nif TYPE_CHECKING:\n from kover.bson import ObjectId\n\nlog = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO)\n\n\nclass User(Document): # noqa: D101\n name: str\n age: int\n\n\nasync def main() -> None: # noqa: D103\n credentials = AuthCredentials.from_environ()\n kover = await Kover.make_client(credentials=credentials)\n\n collection = kover.db.get_collection(\"test\")\n user = User(name=\"John\", age=23)\n file_id: ObjectId = await collection.insert(user) # or user.to_dict()\n\n # this concept requires using \"$set\" explicitly\n # if you dont specify it your entire doc will be\n # just replaced fully to specified here\n # advancements of this way is that you can do anything here not only \"$set\"\n # e.g {\"$push\": {\"userIds\": 12345}} and more\n # in conclusion: be careful with specifying \"$set\", dont forget it!\n update = Update({\"_id\": file_id}, {\"$set\": {\"name\": \"Wick\"}})\n await collection.update(update)\n\n # limit 1 corresponds to .delete_one and 0 to .delete_many\n delete = Delete({\"_id\": file_id}, limit=1)\n n = await collection.delete(delete)\n log.info(f\"documents deleted: {n}\") # 1\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n\n```\n\n# If you found a bug, go ahead and open an issue, or even better a pull request, thx \u2764\ufe0f",
"bugtrack_url": null,
"license": null,
"summary": "Fully async mongodb driver for mongod and replica sets.",
"version": "2.3.0",
"project_urls": {
"Documentation": "https://github.com/megawattka/kover",
"Repository": "https://github.com/megawattka/kover"
},
"split_keywords": [
"kover api mongo",
" mongo kover",
" async driver",
" kover",
" kover mongodb",
" megawattka",
" mongo async",
" mongo kover",
" mongod driver",
" mongodb"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "1737b789fb7042f409a890550957936fc13afafe02dde93d3ab366715f180901",
"md5": "446a2dacbb6e097fd43f91d73b485910",
"sha256": "4a4cf3d76ffe415cfa2132181ee9d15d0918cce4a5167e405e8f3d9705e7b790"
},
"downloads": -1,
"filename": "kover-2.3.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "446a2dacbb6e097fd43f91d73b485910",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.10",
"size": 118360,
"upload_time": "2025-07-19T16:12:06",
"upload_time_iso_8601": "2025-07-19T16:12:06.703336Z",
"url": "https://files.pythonhosted.org/packages/17/37/b789fb7042f409a890550957936fc13afafe02dde93d3ab366715f180901/kover-2.3.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "09bd70f3b1eeb998beeed88c4d6df5c76dbbf525155b748de71363a83253aa86",
"md5": "0d3725674b66b18aa8ffda97216ae70e",
"sha256": "7a30de9fbcf7186ff61a2990b759710eb05c1fc120f3ecfb039caf0274dee267"
},
"downloads": -1,
"filename": "kover-2.3.0.tar.gz",
"has_sig": false,
"md5_digest": "0d3725674b66b18aa8ffda97216ae70e",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.10",
"size": 89471,
"upload_time": "2025-07-19T16:12:08",
"upload_time_iso_8601": "2025-07-19T16:12:08.580805Z",
"url": "https://files.pythonhosted.org/packages/09/bd/70f3b1eeb998beeed88c4d6df5c76dbbf525155b748de71363a83253aa86/kover-2.3.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-07-19 16:12:08",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "megawattka",
"github_project": "kover",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [
{
"name": "pydantic",
"specs": [
[
">=",
"2.10.6"
]
]
},
{
"name": "typing-extensions",
"specs": [
[
">=",
"4.12.2"
]
]
}
],
"lcname": "kover"
}