-
Is anyone using MongoDB as the database with Starlite? Would like to hear how you went about integrating. Also would love to hear from anyone using Beanie as the ODM. |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 8 replies
-
I've started in on this myself using Beanie, but am running into some interesting behavior. I'm coming from FastAPI, so hopefully I'm just misunderstanding some differences between the frameworks. I initialize Beanie using async def initialize_beanie(state: State) -> None:
settings = get_settings()
cx = AsyncIOMotorClient(settings.mongodb_url, uuidRepresentation="standard")
db = getattr(cx, settings.mongodb_db)
await init_beanie(
database=db,
document_models=[
Widget,
],
allow_index_dropping=True,
)
app = Starlite(
route_handlers=[root, SandboxController],
on_startup=[initialize_beanie],
) I define a model like so: from beanie import Document, Indexed
class Widget(Document):
name: Indexed(str, unique=True)
class Settings: # Beanie configuration
name = "sandbox-widgets"
class Config: # Pydantic configuration
schema_extra = {
"example": {
"name": "Widget Name Goes Here",
},
} Creating new instances is where it gets a little wonky. This code creates the document in the DB, but returns an HTTP 500 with a message of "Unable to serialize response content": @post(
"/widget",
response_description="Add a new Sandbox Widget",
)
async def create_widget(self, data: Widget) -> Widget:
try:
await data.create()
except DuplicateKeyError as e:
raise DuplicateKeyIndexException(e, "widget")
return data If I say @post(
"/parent",
response_description="Add a new Sandbox Widget",
)
async def create_widget(self, data: Widget) -> Widget:
try:
await data.create()
except DuplicateKeyError as e:
raise DuplicateKeyIndexException(e, "widget")
return data.json() Any thoughts on the current approach? |
Beta Was this translation helpful? Give feedback.
-
ok, i've found the issue. Our serializer has the following logic: def default_serializer(value: Any) -> Any:
"""Return the default serializer for a given object based on its type.
Args:
value: A value to serialize
Returns:
A serialized value
Raises:
TypeError: if value is not supported
"""
if isinstance(value, BaseModel):
return value.dict()
if isinstance(value, SecretStr):
return value.get_secret_value()
if isinstance(value, (PurePath, PurePosixPath)):
return str(value)
raise TypeError("unsupported type") When we test {'id': ObjectId('637e5eb67e4586cddb7cfa21'), 'name': 'moishe zuchmir'} If I inspect This value IS NOT json serializable as such. The reason you can use this with fastapi is that it relies on the models buildin JSON method, which we do not. Options on your end:
|
Beta Was this translation helpful? Give feedback.
-
Hi there, |
Beta Was this translation helpful? Give feedback.
-
This can be either solved by using If all you need is serialization into JSON, from msgspec import Raw
from beanie import Document
from starlite import Starlite
app = Starlite([...], type_encoders={Document: lambda d: Raw(d.json().encode("utf-8"))}) This way you can make use of beanies built-in json capabilities. |
Beta Was this translation helpful? Give feedback.
-
For Starlite >= 1.48.0, see #1072 |
Beta Was this translation helpful? Give feedback.
For Starlite >= 1.48.0, see #1072