Skip to content

Commit

Permalink
Merge branch 'main' into dto-codegen
Browse files Browse the repository at this point in the history
  • Loading branch information
provinzkraut committed Sep 30, 2023
2 parents e7f563b + 2d7ad67 commit 1bbb2ef
Show file tree
Hide file tree
Showing 26 changed files with 611 additions and 439 deletions.
4 changes: 3 additions & 1 deletion .all-contributorsrc
Original file line number Diff line number Diff line change
Expand Up @@ -1267,7 +1267,9 @@
"avatar_url": "https://avatars.githubusercontent.com/u/61031243?v=4",
"profile": "https://github.com/geeshta",
"contributions": [
"doc"
"doc",
"code",
"bug"
]
},
{
Expand Down
8 changes: 8 additions & 0 deletions .devcontainer/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# [Choice] Python version (use -bookworm or -bullseye variants on local arm64/Apple Silicon): 3, 3.11, 3.10, 3.9, 3.8, 3-bookworm, 3.11-bookworm, 3.10-bookworm, 3.9-bookworm, 3.8-bookworm, 3-bullseye, 3.11-bullseye, 3.10-bullseye, 3.9-bullseye, 3.8-bullseye, 3-buster, 3.11-buster, 3.10-buster, 3.9-buster, 3.8-buster
ARG VARIANT=3-bookworm
FROM python:${VARIANT}

RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
&& apt-get purge -y fish

RUN python3 -m pip install --upgrade setuptools cython pip poetry
70 changes: 70 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
{
"name": "litestar-org/litestar",
"build": {
"dockerfile": "./Dockerfile",
"context": "."
},
"features": {
"ghcr.io/devcontainers/features/common-utils:2": {
"installZsh": "true",
"username": "vscode",
"userUid": "1000",
"userGid": "1000",
"upgradePackages": "true"
},
"ghcr.io/devcontainers/features/github-cli:1": {},
"ghcr.io/devcontainers-contrib/features/pre-commit:2": {},
"ghcr.io/devcontainers/features/python:1": "none",
"ghcr.io/devcontainers/features/git:1": {
"version": "latest",
"ppa": "false"
}
},
"customizations": {
"codespaces": {
"openFiles": ["CONTRIBUTING.rst"]
},
"vscode": {
"extensions": [
"mhutchie.git-graph",
"eamodio.gitlens",
"github.vscode-github-actions",
"ms-python.black-formatter",
"ms-python.mypy-type-checker",
"charliermarsh.ruff"
],
"settings": {
"python.editor.defaultFormatter": "ms-python.black-formatter",
"python.defaultInterpreterPath": "${workspaceFolder}/.venv",
"python.terminal.activateEnvInCurrentTerminal": true,
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"python.testing.pytestArgs": ["."],
"python.terminal.launchArgs": ["-X", "dev"],
"terminal.integrated.shell.linux": "/bin/bash",
"terminal.integrated.profiles.linux": {
"bash": {
"path": "bash",
"icon": "terminal-bash"
},
"zsh": {
"path": "zsh"
},
"fish": {
"path": "fish"
}
}
}
}
},
"forwardPorts": [8000],
"postCreateCommand": [
"poetry",
"install",
"--extras",
"full",
"--with",
"docs,lint"
],
"remoteUser": "vscode"
}
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ repos:
sqlalchemy>=2.0.12,
starlette,
structlog,
advanced-alchemy==0.2.1,
advanced-alchemy==0.2.2,
time-machine,
types-beautifulsoup4,
types-python-jose,
Expand Down Expand Up @@ -176,7 +176,7 @@ repos:
rich,
rich-click,
sqlalchemy>=2.0.12,
advanced-alchemy==0.2.1,
advanced-alchemy==0.2.2,
starlette,
structlog,
time-machine,
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
<td align="center" valign="top" width="14.28%"><a href="https://github.com/sean-donoghue"><img src="https://avatars.githubusercontent.com/u/64597271?v=4?s=100" width="100px;" alt="Sean Donoghue"/><br /><sub><b>Sean Donoghue</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=sean-donoghue" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://sykloid.org/"><img src="https://avatars.githubusercontent.com/u/22753?v=4?s=100" width="100px;" alt="P.C. Shyamshankar"/><br /><sub><b>P.C. Shyamshankar</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/issues?q=author%3Asykloid" title="Bug reports">🐛</a> <a href="https://github.com/litestar-org/litestar/commits?author=sykloid" title="Code">💻</a> <a href="https://github.com/litestar-org/litestar/commits?author=sykloid" title="Tests">⚠️</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/wevonosky"><img src="https://avatars.githubusercontent.com/u/19598171?v=4?s=100" width="100px;" alt="William Evonosky"/><br /><sub><b>William Evonosky</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=wevonosky" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/geeshta"><img src="https://avatars.githubusercontent.com/u/61031243?v=4?s=100" width="100px;" alt="geeshta"/><br /><sub><b>geeshta</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=geeshta" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/geeshta"><img src="https://avatars.githubusercontent.com/u/61031243?v=4?s=100" width="100px;" alt="geeshta"/><br /><sub><b>geeshta</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=geeshta" title="Documentation">📖</a> <a href="https://github.com/litestar-org/litestar/commits?author=geeshta" title="Code">💻</a> <a href="https://github.com/litestar-org/litestar/issues?q=author%3Ageeshta" title="Bug reports">🐛</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://fosstodon.org/@robertrosca"><img src="https://avatars.githubusercontent.com/u/32569096?v=4?s=100" width="100px;" alt="Robert Rosca"/><br /><sub><b>Robert Rosca</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=RobertRosca" title="Documentation">📖</a></td>
</tr>
<tr>
Expand Down
2 changes: 2 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@
(PY_CLASS, "advanced_alchemy.types.BigIntIdentity"),
(PY_FUNC, "sqlalchemy.get_engine"),
(PY_ATTR, "advanced_alchemy.repository.AbstractAsyncRepository.id_attribute"),
("py:exc", "RepositoryError"),
]

nitpick_ignore_regex = [
Expand All @@ -179,6 +180,7 @@
(PY_RE, r"litestar\.connection\.base\.UserT"),
(PY_RE, r"litestar\.pagination\.C"),
(PY_RE, r"multidict\..*"),
(PY_RE, r"advanced_alchemy.*\.T"),
]

# Warnings about missing references to those targets in the specified location will be ignored.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ async def delete_author(

async def on_startup() -> None:
"""Initializes the database."""
async with sqlalchemy_config.create_engine().begin() as conn:
async with sqlalchemy_config.get_engine().begin() as conn:
await conn.run_sync(UUIDBase.metadata.create_all)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class Book(UUIDAuditBase):

async def on_startup() -> None:
"""Initializes the database."""
async with sqlalchemy_config.create_engine().begin() as conn:
async with sqlalchemy_config.get_engine().begin() as conn:
await conn.run_sync(UUIDBase.metadata.create_all)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ async def provide_blog_post_repo(db_session: AsyncSession) -> BlogPostRepository

async def on_startup() -> None:
"""Initializes the database."""
async with sqlalchemy_config.create_engine().begin() as conn:
async with sqlalchemy_config.get_engine().begin() as conn:
await conn.run_sync(UUIDAuditBase.metadata.create_all)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ def delete_author(

def on_startup() -> None:
"""Initializes the database."""
with sqlalchemy_config.create_engine().begin() as conn:
with sqlalchemy_config.get_engine().begin() as conn:
UUIDBase.metadata.create_all(conn)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ async def people_handler(paginator: PersonOffsetPaginator, limit: int, offset: i

async def on_startup() -> None:
"""Initializes the database."""
async with sqlalchemy_config.create_engine().begin() as conn:
async with sqlalchemy_config.get_engine().begin() as conn:
await conn.run_sync(UUIDBase.metadata.create_all)


Expand Down
3 changes: 1 addition & 2 deletions docs/reference/repository/exceptions.rst
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
exceptions
==========

.. automodule:: litestar.repository.exceptions
:members:
This page has moved to :doc:`advanced-alchemy:reference/filters`
3 changes: 1 addition & 2 deletions docs/reference/repository/filters.rst
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
filters
=======

.. automodule:: litestar.repository.filters
:members:
This page has moved to :doc:`advanced-alchemy:reference/filters`
3 changes: 2 additions & 1 deletion litestar/_openapi/schema_generation/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
create_numerical_constrained_field_schema,
create_string_constrained_field_schema,
)
from litestar._openapi.schema_generation.examples import create_examples_for_field
from litestar._openapi.schema_generation.utils import sort_schemas_and_references
from litestar.datastructures import UploadFile
from litestar.exceptions import ImproperlyConfiguredException
Expand Down Expand Up @@ -586,6 +585,8 @@ def process_schema_result(self, field: FieldDefinition, schema: Schema) -> Schem
setattr(schema, schema_key, value)

if not schema.examples and self.generate_examples:
from litestar._openapi.schema_generation.examples import create_examples_for_field

schema.examples = create_examples_for_field(field)

if schema.title and schema.type in (OpenAPIType.OBJECT, OpenAPIType.ARRAY):
Expand Down
28 changes: 15 additions & 13 deletions litestar/dto/_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
"""
from __future__ import annotations

import secrets
from dataclasses import replace
from typing import TYPE_CHECKING, AbstractSet, Any, Callable, ClassVar, Collection, Final, Mapping, Union, cast

Expand All @@ -27,6 +26,7 @@
from litestar.serialization import decode_json, decode_msgpack
from litestar.types import Empty
from litestar.typing import FieldDefinition
from litestar.utils import unique_name_for_scope
from litestar.utils.typing import safe_generic_origin_map

if TYPE_CHECKING:
Expand Down Expand Up @@ -154,6 +154,18 @@ def parse_model(
defined_fields.append(transfer_field_definition)
return tuple(defined_fields)

def _create_transfer_model_name(self, model_name: str) -> str:
long_name_prefix = self.handler_id.split("::")[0]
short_name_prefix = _camelize(long_name_prefix.split(".")[-1], True)

name_suffix = "RequestBody" if self.is_data_field else "ResponseBody"

if (short_name := f"{short_name_prefix}{model_name}{name_suffix}") not in self._seen_model_names:
return short_name
if (long_name := f"{long_name_prefix}{model_name}{name_suffix}") not in self._seen_model_names:
return long_name
return unique_name_for_scope(long_name, self._seen_model_names)

def create_transfer_model_type(
self, model_name: str, field_definitions: tuple[TransferDTOFieldDefinition, ...]
) -> type[Struct]:
Expand All @@ -166,19 +178,9 @@ def create_transfer_model_type(
Returns:
A ``BackendT`` class.
"""
long_name_prefix = self.handler_id.split("::")[0]
short_name_prefix = _camelize(long_name_prefix.split(".")[-1], True)

name_suffix = "RequestBody" if self.is_data_field else "ResponseBody"

if f"{short_name_prefix}{model_name}{name_suffix}" not in self._seen_model_names:
struct_name = f"{short_name_prefix}{model_name}{name_suffix}"
elif f"{long_name_prefix}{model_name}{name_suffix}" not in self._seen_model_names:
struct_name = f"{long_name_prefix}{model_name}{name_suffix}"
else:
struct_name = f"{long_name_prefix}{model_name}{name_suffix}{secrets.token_hex(8)}"

struct_name = self._create_transfer_model_name(model_name)
self._seen_model_names.add(struct_name)

struct = _create_struct_for_field_definitions(struct_name, field_definitions)
setattr(struct, "__schema_name__", struct_name)
return struct
Expand Down
15 changes: 0 additions & 15 deletions litestar/handlers/http_handlers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -435,11 +435,6 @@ def get_response_handler(self, is_response_type_data: bool = False) -> Callable[
return_type = self.parsed_fn_signature.return_type
return_annotation = return_type.annotation

if before_request_handler := self.resolve_before_request():
handler_return_type = before_request_handler.parsed_signature.return_type
if not handler_return_type.is_subclass_of((Empty, NoneType)):
return_annotation = handler_return_type.annotation

self._response_handler_mapping["response_type_handler"] = response_type_handler = create_response_handler(
after_request=after_request,
background=self.background,
Expand Down Expand Up @@ -494,9 +489,6 @@ async def to_response(self, app: Litestar, data: Any, request: Request) -> ASGIA
return await response_handler(app=app, data=data, request=request) # type: ignore

def on_registration(self, app: Litestar) -> None:
if before_request := self.resolve_before_request():
before_request.set_parsed_signature(self.resolve_signature_namespace())

super().on_registration(app)
self.resolve_after_response()
self.resolve_include_in_schema()
Expand Down Expand Up @@ -527,13 +519,6 @@ def _validate_handler_function(self) -> None:
"If the function should return a value, change the route handler status code to an appropriate value.",
)

if (
(before_request := self.resolve_before_request())
and not before_request.parsed_signature.return_type.is_subclass_of(NoneType)
and not before_request.parsed_signature.return_type.is_optional
):
return_type = before_request.parsed_signature.return_type

if not self.media_type:
if return_type.is_subclass_of((str, bytes)) or return_type.annotation is AnyStr:
self.media_type = MediaType.TEXT
Expand Down
15 changes: 15 additions & 0 deletions litestar/repository/_exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from __future__ import annotations

__all__ = ("ConflictError", "NotFoundError", "RepositoryError")


class RepositoryError(Exception):
"""Base repository exception type."""


class ConflictError(RepositoryError):
"""Data integrity error."""


class NotFoundError(RepositoryError):
"""An identity does not exist."""
Loading

0 comments on commit 1bbb2ef

Please sign in to comment.