Skip to content

Commit

Permalink
fix conflicts after merge from master
Browse files Browse the repository at this point in the history
  • Loading branch information
collerek committed Dec 5, 2024
2 parents cf303fc + 56102a4 commit cabee1f
Show file tree
Hide file tree
Showing 10 changed files with 1,273 additions and 1,589 deletions.
22 changes: 12 additions & 10 deletions docs/fastapi/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Here you can find a very simple sample application code.
Define startup and shutdown procedures using FastAPI lifespan and use is in the
application.
```python
from typing import List, Optional
from typing import List, Optional, AsyncIterator

import databases
import sqlalchemy
Expand All @@ -41,22 +41,24 @@ from contextlib import asynccontextmanager
from fastapi import FastAPI


@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
if not config.database.is_connected:
await config.database.connect()
def get_lifespan(config):
@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
if not config.database.is_connected:
await config.database.connect()

yield

if config.database.is_connected:
await config.database.disconnect()
yield

if config.database.is_connected:
await config.database.disconnect()
return lifespan

base_ormar_config = ormar.OrmarConfig(
metadata=sqlalchemy.MetaData(),
database=databases.Database("sqlite:///test.db"),
)
app = FastAPI(lifespan=lifespan(base_ormar_config))

app = FastAPI(lifespan=get_lifespan(base_ormar_config))
```

!!!info
Expand Down
6 changes: 5 additions & 1 deletion ormar/models/helpers/relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,11 @@ def expand_reverse_relationships(model: Type["Model"]) -> None:
"""
model_fields = list(model.ormar_config.model_fields.values())
for model_field in model_fields:
if model_field.is_relation and not model_field.has_unresolved_forward_refs():
if (
model_field.is_relation
and not model_field.has_unresolved_forward_refs()
and not model_field.is_through
):
model_field = cast("ForeignKeyField", model_field)
expand_reverse_relationship(model_field=model_field)

Expand Down
9 changes: 7 additions & 2 deletions ormar/models/mixins/save_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
cast,
)

from pydantic.plugin._schema_validator import create_schema_validator
from pydantic.plugin._schema_validator import (
PluggableSchemaValidator,
create_schema_validator,
)
from pydantic_core import CoreSchema, SchemaValidator

import ormar # noqa: I100, I202
Expand All @@ -36,7 +39,9 @@ class SavePrepareMixin(RelationMixin, AliasMixin):
_json_fields: Set[str]
_bytes_fields: Set[str]
__pydantic_core_schema__: CoreSchema
__ormar_fields_validators__: Optional[Dict[str, SchemaValidator]]
__ormar_fields_validators__: Optional[
Dict[str, SchemaValidator | PluggableSchemaValidator]
]

@classmethod
def prepare_model_to_save(cls, new_kwargs: dict) -> dict:
Expand Down
2 changes: 1 addition & 1 deletion ormar/queryset/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def translate_list_to_dict( # noqa: CCR001
for path in list_to_trans:
current_level = new_dict
parts = path.split("__")
def_val: Any = default
def_val: Any = copy.deepcopy(default)
for ind, part in enumerate(parts):
is_last = ind == len(parts) - 1
if check_node_not_dict_or_not_last_node(
Expand Down
2,757 changes: 1,190 additions & 1,567 deletions poetry.lock

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ classifiers = [
[tool.poetry.dependencies]
python = "^3.8.0"
databases = "^0.7.0"
pydantic = "v2.5.3"
pydantic = ">=2.5.3,<2.9.0"
SQLAlchemy = "^1.4.42"
cryptography = { version = ">=41.0.3,<43.0.0", optional = true }
cryptography = { version = ">=41.0.3,<44.0.0", optional = true }
# Async database drivers
aiosqlite = { version = ">=0.19,<0.21", optional = true }
aiomysql = { version = ">=0.1.0", optional = true }
Expand Down Expand Up @@ -89,7 +89,7 @@ pytest = ">=7.4.4,<9.0.0"
pytest-cov = ">=4,<6"
codecov = "^2.1.13"
pytest-asyncio = ">=0.21,<0.24"
fastapi = ">=0.109.1,<0.112.0"
fastapi = ">=0.109.1,<0.115.6"

black = "^24.1.0"
ruff = ">=0.5.1,<0.5.2"
Expand Down
6 changes: 2 additions & 4 deletions tests/test_fastapi/test_binary_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,8 @@ async def test_read_main():
)
assert response.status_code == 200
response = await client.get("/things")
assert response.json()[0]["bt"] == blob3.decode()
resp_json = response.json()
resp_json[0]["bt"] = resp_json[0]["bt"].encode()
thing = BinaryThing(**resp_json[0])
assert response.json()[0]["bt"] == base64.b64encode(blob3).decode()
thing = BinaryThing(**response.json()[0])
assert thing.__dict__["bt"] == blob3
assert thing.bt == base64.b64encode(blob3).decode()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@ def test_constraints():

with pytest.raises(
ValidationError,
match="The email address is not valid. It must have exactly one @-sign",
match=(
r"The email address is not valid. It must have exactly one @-sign|"
r"An email address must have an @-sign"
),
):
User(email="wrong")

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import ormar
import pytest

from tests.lifespan import init_tests
from tests.settings import create_config

base_ormar_config = create_config()


class Author(ormar.Model):
ormar_config = base_ormar_config.copy(tablename="authors")

id = ormar.Integer(primary_key=True)
name = ormar.String(max_length=100)


class Book(ormar.Model):
ormar_config = base_ormar_config.copy(tablename="books")

id = ormar.Integer(primary_key=True)
title = ormar.String(max_length=100)
author = ormar.ManyToMany(
Author,
)
year = ormar.Integer(nullable=True)


create_test_database = init_tests(base_ormar_config)


@pytest.mark.asyncio
async def test_tables_are_created():
async with base_ormar_config.database:
assert await Book.objects.all() == []
15 changes: 15 additions & 0 deletions tests/test_utils/test_queryset_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,21 @@ def test_list_to_dict_translation():
}


def test_list_to_dict_translation_with_default():
tet_list = ["aa", "aa__inner", "bb"]
testshallow = translate_list_to_dict(tet_list, default={})
assert testshallow == {"aa": {"inner": {}}, "bb": {}}

tet_list = ["aa", "aa__inner", "bb"]
testdeep = translate_list_to_dict(tet_list, default={"foo": {}})
assert testdeep == {"aa": {"foo": {}, "inner": {"foo": {}}}, "bb": {"foo": {}}}
testdeep["aa"]["foo"]["bar"] = 1234
assert testdeep == {
"aa": {"foo": {"bar": 1234}, "inner": {"foo": {}}},
"bb": {"foo": {}},
}


def test_updating_dict_with_list():
curr_dict = {
"aa": Ellipsis,
Expand Down

0 comments on commit cabee1f

Please sign in to comment.