Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add cache store parameter on route level basis #3869

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
4894593
fix: (typo) changed emphasis from line 12 to 11 to highlight the corr…
eliasfandi Sep 30, 2024
63b3b3f
fix: sign bug in rate limit middelware (#3776)
pogopaule Oct 3, 2024
1e55ef3
docs: add pogopaule as a contributor for code (#3777)
allcontributors[bot] Oct 3, 2024
e7dfc7a
fix: map JSONSchema spec naming convention to snake_case when names f…
charles-dyfis-net Oct 3, 2024
e18aa3d
docs(readme): Remove reference to `litestar-pg-redis-docker` (#3779)
Alc-Alc Oct 5, 2024
600451e
chore(devcontainer): Fix python version in devcontainer (#3790)
sobolevn Oct 14, 2024
bc7a0ce
docs: Fix python code highlight in many examples (#3788)
sobolevn Oct 14, 2024
ad592f6
docs: fix a typo in `requests` usage docs (#3794)
sobolevn Oct 14, 2024
6493543
docs: fix typos in `sqlalchemy` examples (#3798)
sobolevn Oct 14, 2024
39b4ed2
docs: fix typos in `sqlalchemy/models_and_repository.rst` (#3797)
sobolevn Oct 14, 2024
1a4f1a3
docs: fix missing import in `cache` usage (#3795)
sobolevn Oct 15, 2024
173098b
docs: make sure that `channels` use `finally` in all examples (#3796)
sobolevn Oct 15, 2024
fdb4f3d
docs: change the `ExperimentalFeatures.DTO_CODEGEN` description (#3802)
sobolevn Oct 15, 2024
2305719
docs: change `sync-to-thread-info.rst` wording about `sync_to_thread`…
sobolevn Oct 15, 2024
cf3217f
docs: add missing rename strategy to `dto` docs (#3805)
sobolevn Oct 15, 2024
45df0bf
docs: fix highlighted lines in DTO usage (#3808)
sobolevn Oct 15, 2024
c5421e5
fix: typo in a deprecation warning in `contrib/sqlalchemy/plugins/ser…
sobolevn Oct 16, 2024
236cfa3
chore(ci): fix the `pr_merged.yml` workflow (#3811)
sobolevn Oct 16, 2024
a7cd193
chore(mypy): enable more mypy codes (#3817)
sobolevn Oct 16, 2024
50e1ad2
docs: fix "DTO Factory and PATCH requests" section (#3819)
sobolevn Oct 16, 2024
682e4c7
chore(mypy): enable `possibly-undefined` error code (#3818)
sobolevn Oct 16, 2024
45d5ec1
docs: fix `DTO Data` section with a new example (#3813)
sobolevn Oct 17, 2024
f534f52
docs: fix highlight of code example in "Providing values for nested d…
sobolevn Oct 17, 2024
d060d41
docs: rewrite htmx guide (#3825)
sobolevn Oct 17, 2024
6f79fb3
docs: refactor "Hooks" usage documentation (#3826)
sobolevn Oct 18, 2024
0e32aae
docs: fix API reference for `asgi_types` scopes (#3831)
sobolevn Oct 18, 2024
a1b530c
docs: rewrite "Builtin middleware" usage (#3830)
sobolevn Oct 19, 2024
fd3ff42
fix(prometheus): fix path template for routes without path parameters…
mohammedbabelly20 Oct 19, 2024
f7b258f
docs: add mohammedbabelly20 as a contributor for code (#3832)
allcontributors[bot] Oct 19, 2024
b2adb0d
docs: refactor "Custom Middleware" guide (#3833)
sobolevn Oct 19, 2024
5255ec3
fix: LifespanHandler memory stream cleanup (#3836)
provinzkraut Oct 21, 2024
91ec7a3
fix: set correct path_template value for trie node (#3806) (#3807)
wallseat Oct 22, 2024
ffcecb1
docs: refactor exception usage (#3823)
sobolevn Oct 23, 2024
017464f
feat: implement `HTMX` plugin using `litestar-htmx` (#3837)
cofin Oct 24, 2024
dcae3b3
feat(Pydantic): honor `hide_input_in_errors` in throwing validation e…
charles-dyfis-net Oct 29, 2024
da4cc0b
docs: add charles-dyfis-net as a contributor for code (#3844)
allcontributors[bot] Oct 29, 2024
ed35b61
fix: Safe Handling of "more_body" in ASGI Responses (#3845)
cemrehancavdar Oct 30, 2024
c354e36
chore(mypy): enable `truthy-bool` error code (#3824)
sobolevn Nov 2, 2024
f00f87d
docs: remove references to `python-jose` (#3847)
cofin Nov 6, 2024
4b88735
fix: Duplicate `RateLimit-*` headers with caching (#3855)
mohammedbabelly20 Nov 12, 2024
999aedb
docs: add RenameMe1 as a contributor for doc (#3858)
allcontributors[bot] Nov 14, 2024
0fdbfa3
docs: Changing incorrect indentation in the code example "creating-m…
RenameMe1 Nov 14, 2024
ee90e96
docs: improve `openapi/index.rst` page (#3856)
sobolevn Nov 14, 2024
757a460
chore(deps): bump codecov/codecov-action from 4 to 5 (#3859)
dependabot[bot] Nov 15, 2024
98933a3
docs: fix the description of when to use the synchronous function (#3…
vvanglro Nov 16, 2024
a2b8e48
feat: deprecate `litestar.contrib.pydantic` (#3852)
cofin Nov 16, 2024
1b2ef9a
docs: Added debug=True in Testing to display exception stack trace (#…
RenameMe1 Nov 17, 2024
a3631e2
fix(typing): Fix typing in websocket listener class (#3765)
olzhasar Nov 17, 2024
7e56814
docs: add olzhasar as a contributor for bug, and doc (#3865)
allcontributors[bot] Nov 17, 2024
53c1473
Merge commit from fork
provinzkraut Nov 20, 2024
1b9d1c8
v2.13.0
provinzkraut Nov 20, 2024
44d42e6
feat: deprecate `litestar.contrib.prometheus` (#3863)
cofin Nov 21, 2024
c651589
feat: add cache store parameter
dylandoamaral Nov 21, 2024
28fa61c
chore: fix format
dylandoamaral Nov 21, 2024
15c3893
Merge branch 'main' into feat/add-cache-store-parameter
dylandoamaral Nov 21, 2024
0599e3f
chore: fix format
dylandoamaral Nov 21, 2024
e39b1b4
Merge branch 'feat/add-cache-store-parameter' of github.com:dylandoam…
dylandoamaral Nov 21, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions .all-contributorsrc
Original file line number Diff line number Diff line change
Expand Up @@ -1868,6 +1868,52 @@
"contributions": [
"doc"
]
},
{
"login": "pogopaule",
"name": "Fabian",
"avatar_url": "https://avatars.githubusercontent.com/u/576949?v=4",
"profile": "https://github.com/pogopaule",
"contributions": [
"code"
]
},
{
"login": "mohammedbabelly20",
"name": "Mohammed Babelly",
"avatar_url": "https://avatars.githubusercontent.com/u/104768048?v=4",
"profile": "https://github.com/mohammedbabelly20",
"contributions": [
"code"
]
},
{
"login": "charles-dyfis-net",
"name": "Charles Duffy",
"avatar_url": "https://avatars.githubusercontent.com/u/22370?v=4",
"profile": "https://keybase.io/charlesdyfisnet",
"contributions": [
"code"
]
},
{
"login": "RenameMe1",
"name": "Evgeny Demchenko",
"avatar_url": "https://avatars.githubusercontent.com/u/165988121?v=4",
"profile": "https://github.com/RenameMe1",
"contributions": [
"doc"
]
},
{
"login": "olzhasar",
"name": "Olzhas Arystanov",
"avatar_url": "https://avatars.githubusercontent.com/u/12471703?v=4",
"profile": "https://olzhasar.com",
"contributions": [
"bug",
"doc"
]
}
],
"contributorsPerLine": 7,
Expand Down
4 changes: 2 additions & 2 deletions .devcontainer/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# [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
# [Choice] Python version (use -bookworm or -bullseye variants on local arm64/Apple Silicon): 3, 3.13, 3.12, 3.11, 3.10, 3.9, 3.8, 3-bookworm, 3.13-bookworm, 3.12-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.12-bookworm
FROM python:${VARIANT}

RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ jobs:
run: sed -i "s/home\/runner\/work\/litestar\/litestar/github\/workspace/g" coverage.xml

- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v4
uses: codecov/codecov-action@v5
with:
files: coverage.xml
token: ${{ secrets.CODECOV_TOKEN }}
7 changes: 2 additions & 5 deletions .github/workflows/pr-merged.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,8 @@ jobs:
script: |
const prNumber = context.payload.number
const branch = context.baseRef
# TODO: `develop` no longer exists. Need a new way to determine if the
# change will be introduced in a major, minor, or patch release.
# possibly conventional commit standards in the PR title or by labels?
const isDevelop = branch === "develop"
const commentBody = `<!--closing-comment-->\nThis issue has been closed in #${prNumber}. The change will be included in the upcoming ${isDevelop ? "minor" : "patch"} release.`
// TODO: use semantic commits to specify the exact version, when it will be released
const commentBody = `<!--closing-comment-->\nThis issue has been closed in #${prNumber}. The change will be included in upcoming releases.`

const query = `query($number: Int!, $owner: String!, $name: String!) { repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
Expand Down
10 changes: 5 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
default_language_version:
python: "3.8"
python: "3"
repos:
- repo: https://github.com/compilerla/conventional-pre-commit
rev: v3.4.0
rev: v3.6.0
hooks:
- id: conventional-pre-commit
stages: [commit-msg]
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
rev: v5.0.0
hooks:
- id: check-ast
- id: check-case-conflict
Expand All @@ -24,7 +24,7 @@ repos:
- id: unasyncd
additional_dependencies: ["ruff"]
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: "v0.6.2"
rev: "v0.7.3"
hooks:
- id: ruff
args: ["--fix"]
Expand All @@ -43,7 +43,7 @@ repos:
exclude: "test*|examples*|tools"
args: ["--use-tuple"]
- repo: https://github.com/sphinx-contrib/sphinx-lint
rev: "v0.9.1"
rev: "v1.0.0"
hooks:
- id: sphinx-lint
- repo: local
Expand Down
1 change: 1 addition & 0 deletions CONTRIBUTING.rst
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,7 @@ Please follow the next guidelines when adding a new example:
:caption: An example of how to use literal includes of external files

.. literalinclude:: /examples/test_thing.py
:language: python
:caption: All includes should have a descriptive caption

Automatically execute examples
Expand Down
15 changes: 10 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,11 @@ app = Litestar(route_handlers=[hello_world])
<details>
<summary>Pre-built Example Apps</summary>

- [litestar-pg-redis-docker](https://github.com/litestar-org/litestar-pg-redis-docker): In addition to Litestar, this
demonstrates a pattern of application modularity, SQLAlchemy 2.0 ORM, Redis cache connectivity, and more. Like all
Litestar projects, this application is open to contributions, big and small.
- [litestar-fullstack](https://github.com/litestar-org/litestar-fullstack): A reference application that contains most of the boilerplate required for a web application.
It features a Litestar app configured with best practices, SQLAlchemy 2.0 and SAQ, a frontend integrated with Vitejs and Jinja2 templates, Docker, and more.
- [litestar-hello-world](https://github.com/litestar-org/litestar-hello-world): A bare-minimum application setup. Great
for testing and POC work.
- [litestar-fullstack](https://github.com/litestar-org/litestar-fullstack): A reference application that contains most of the boilerplate required for a web application.
It features a Litestar app configured with best practices, SQLAlchemy 2.0 and SAQ, a frontend integrated with Vitejs and Jinja2 templates, Docker, and more. Like all
Litestar projects, this application is open to contributions, big and small.
</details>

## Sponsors
Expand Down Expand Up @@ -578,6 +576,13 @@ see [the contribution guide](CONTRIBUTING.rst).
<td align="center" valign="top" width="14.28%"><a href="https://blog.trim21.me/"><img src="https://avatars.githubusercontent.com/u/13553903?v=4?s=100" width="100px;" alt="Trim21"/><br /><sub><b>Trim21</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=trim21" title="Code">💻</a> <a href="https://github.com/litestar-org/litestar/commits?author=trim21" title="Tests">⚠️</a></td>
<td align="center" valign="top" width="14.28%"><a href="http://aarcex3.github.io"><img src="https://avatars.githubusercontent.com/u/59893355?v=4?s=100" width="100px;" alt="Agustin Arce"/><br /><sub><b>Agustin Arce</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=aarcex3" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/FarhanAliRaza"><img src="https://avatars.githubusercontent.com/u/62690310?v=4?s=100" width="100px;" alt="Farhan Ali Raza"/><br /><sub><b>Farhan Ali Raza</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=FarhanAliRaza" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/pogopaule"><img src="https://avatars.githubusercontent.com/u/576949?v=4?s=100" width="100px;" alt="Fabian"/><br /><sub><b>Fabian</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=pogopaule" title="Code">💻</a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/mohammedbabelly20"><img src="https://avatars.githubusercontent.com/u/104768048?v=4?s=100" width="100px;" alt="Mohammed Babelly"/><br /><sub><b>Mohammed Babelly</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=mohammedbabelly20" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://keybase.io/charlesdyfisnet"><img src="https://avatars.githubusercontent.com/u/22370?v=4?s=100" width="100px;" alt="Charles Duffy"/><br /><sub><b>Charles Duffy</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=charles-dyfis-net" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/RenameMe1"><img src="https://avatars.githubusercontent.com/u/165988121?v=4?s=100" width="100px;" alt="Evgeny Demchenko"/><br /><sub><b>Evgeny Demchenko</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/commits?author=RenameMe1" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://olzhasar.com"><img src="https://avatars.githubusercontent.com/u/12471703?v=4?s=100" width="100px;" alt="Olzhas Arystanov"/><br /><sub><b>Olzhas Arystanov</b></sub></a><br /><a href="https://github.com/litestar-org/litestar/issues?q=author%3Aolzhasar" title="Bug reports">🐛</a> <a href="https://github.com/litestar-org/litestar/commits?author=olzhasar" title="Documentation">📖</a></td>
</tr>
</tbody>
</table>
Expand Down
8 changes: 3 additions & 5 deletions docs/PYPI_README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,11 @@ app = Litestar(route_handlers=[hello_world])
<details>
<summary>Pre-built Example Apps</summary>

- [litestar-pg-redis-docker](https://github.com/litestar-org/litestar-pg-redis-docker): In addition to Litestar, this
demonstrates a pattern of application modularity, SQLAlchemy 2.0 ORM, Redis cache connectivity, and more. Like all
Litestar projects, this application is open to contributions, big and small.
- [litestar-fullstack](https://github.com/litestar-org/litestar-fullstack): A reference application that contains most of the boilerplate required for a web application.
It features a Litestar app configured with best practices, SQLAlchemy 2.0 and SAQ, a frontend integrated with Vitejs and Jinja2 templates, Docker, and more.
- [litestar-hello-world](https://github.com/litestar-org/litestar-hello-world): A bare-minimum application setup. Great
for testing and POC work.
- [litestar-fullstack](https://github.com/litestar-org/litestar-fullstack): A reference application that contains most of the boilerplate required for a web application.
It features a Litestar app configured with best practices, SQLAlchemy 2.0 and SAQ, a frontend integrated with Vitejs and Jinja2 templates, Docker, and more. Like all
Litestar projects, this application is open to contributions, big and small.
</details>

## Sponsors
Expand Down
7 changes: 5 additions & 2 deletions docs/admonitions/sync-to-thread-info.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
running the event loop, and in turn block the whole application.

To mitigate this, the ``sync_to_thread`` parameter can be set to ``True``, which
will result in the function being run in a thread pool. Should the function be
non-blocking, ``sync_to_thread`` should be set to ``False`` instead.
will result in the function being run in a thread pool.

If a synchronous function is non-blocking, setting ``sync_to_thread`` to ``False``
will tell Litestar that the user is sure about its behavior
and the function can be treated as non-blocking.

If a synchronous function is passed, without setting an explicit ``sync_to_thread``
value, a warning will be raised.
Expand Down
11 changes: 11 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@
(PY_CLASS, "litestar.contrib.sqlalchemy.dto.SQLAlchemyDTO"),
(PY_CLASS, "litestar.contrib.sqlalchemy.types.BigIntIdentity"),
(PY_CLASS, "litestar.contrib.sqlalchemy.types.JsonB"),
(PY_CLASS, "litestar.contrib.htmx.request.HTMXRequest"),
(PY_CLASS, "litestar.typing.ParsedType"),
(PY_METH, "litestar.dto.factory.DTOData.create_instance"),
(PY_METH, "litestar.dto.interface.DTOInterface.data_to_encodable_type"),
Expand Down Expand Up @@ -191,6 +192,16 @@
(PY_CLASS, "litestar.template.Template"),
(PY_CLASS, "litestar.middleware.compression.gzip_facade.GzipCompression"),
(PY_CLASS, "litestar.handlers.http_handlers.decorators._subclass_warning"),
(PY_CLASS, "litestar.background_tasks.P"),
(PY_CLASS, "P.args"),
(PY_CLASS, "P.kwargs"),
(PY_CLASS, "litestar.contrib.jinja.P"),
(PY_CLASS, "litestar.contrib.mako.P"),
(PY_CLASS, "JWTDecodeOptions"),
(PY_CLASS, "litestar.template.base.P"),
(PY_CLASS, "litestar.contrib.pydantic.PydanticDTO"),
(PY_CLASS, "litestar.contrib.pydantic.PydanticPlugin"),
(PY_CLASS, "typing.Self"),
]

nitpick_ignore_regex = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ class BaseModel(_BaseModel):
model_config = {"from_attributes": True}


# the SQLAlchemy base includes a declarative model for you to use in your models.
# The `Base` class includes a `UUID` based primary key (`id`)
# The SQLAlchemy base includes a declarative model for you to use in your models.
# The `UUIDBase` class includes a `UUID` based primary key (`id`)
class AuthorModel(base.UUIDBase):
# we can optionally provide the table name instead of auto-generating it
__tablename__ = "author" # type: ignore[assignment]
Expand All @@ -44,9 +44,9 @@ class AuthorModel(base.UUIDBase):
books: Mapped[list[BookModel]] = relationship(back_populates="author", lazy="noload")


# The `AuditBase` class includes the same UUID` based primary key (`id`) and 2
# additional columns: `created` and `updated`. `created` is a timestamp of when the
# record created, and `updated` is the last time the record was modified.
# The `UUIDAuditBase` class includes the same UUID` based primary key (`id`) and 2
# additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the
# record created, and `updated_at` is the last time the record was modified.
class BookModel(base.UUIDAuditBase):
__tablename__ = "book" # type: ignore[assignment]
title: Mapped[str]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@
from litestar.contrib.sqlalchemy.plugins import AsyncSessionConfig, SQLAlchemyAsyncConfig, SQLAlchemyPlugin


# the SQLAlchemy base includes a declarative model for you to use in your models.
# The `Base` class includes a `UUID` based primary key (`id`)
# The SQLAlchemy base includes a declarative model for you to use in your models.
# The `UUIDBase` class includes a `UUID` based primary key (`id`)
class Author(UUIDBase):
name: Mapped[str]
dob: Mapped[date]
books: Mapped[List[Book]] = relationship(back_populates="author", lazy="selectin")


# The `AuditBase` class includes the same UUID` based primary key (`id`) and 2
# The `UUIDAuditBase` class includes the same UUID` based primary key (`id`) and 2
# additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the
# record created, and `updated_at` is the last time the record was modified.
class Book(UUIDAuditBase):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,9 @@ async def _is_slug_unique(
return await self.get_one_or_none(slug=slug) is None


# The `AuditBase` class includes the same UUID` based primary key (`id`) and 2
# additional columns: `created` and `updated`. `created` is a timestamp of when the
# record created, and `updated` is the last time the record was modified.
# The `UUIDAuditBase` class includes the same UUID` based primary key (`id`) and 2
# additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the
# record created, and `updated_at` is the last time the record was modified.
class BlogPost(UUIDAuditBase, SlugKey):
title: Mapped[str]
content: Mapped[str]
Expand Down
10 changes: 5 additions & 5 deletions docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ class BaseModel(_BaseModel):
model_config = {"from_attributes": True}


# the SQLAlchemy base includes a declarative model for you to use in your models.
# The `Base` class includes a `UUID` based primary key (`id`)
# The SQLAlchemy base includes a declarative model for you to use in your models.
# The `UUIDBase` class includes a `UUID` based primary key (`id`)
class AuthorModel(UUIDBase):
# we can optionally provide the table name instead of auto-generating it
__tablename__ = "author" # type: ignore[assignment]
Expand All @@ -40,9 +40,9 @@ class AuthorModel(UUIDBase):
books: Mapped[list[BookModel]] = relationship(back_populates="author", lazy="noload")


# The `AuditBase` class includes the same UUID` based primary key (`id`) and 2
# additional columns: `created` and `updated`. `created` is a timestamp of when the
# record created, and `updated` is the last time the record was modified.
# The `UUIDAuditBase` class includes the same UUID` based primary key (`id`) and 2
# additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the
# record created, and `updated_at` is the last time the record was modified.
class BookModel(UUIDAuditBase):
__tablename__ = "book" # type: ignore[assignment]
title: Mapped[str]
Expand Down
11 changes: 4 additions & 7 deletions docs/examples/data_transfer_objects/factory/patch_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,14 @@ class PatchDTO(DataclassDTO[Person]):
config = DTOConfig(exclude={"id"}, partial=True)


database = {
UUID("f32ff2ce-e32f-4537-9dc0-26e7599f1380"): Person(
id=UUID("f32ff2ce-e32f-4537-9dc0-26e7599f1380"), name="Peter", age=40
)
}
peter_uuid = UUID("f32ff2ce-e32f-4537-9dc0-26e7599f1380")
database = {peter_uuid: Person(id=peter_uuid, name="Peter", age=40)}


@patch("/person/{person_id:uuid}", dto=PatchDTO, return_dto=None, sync_to_thread=False)
def update_person(person_id: UUID, data: DTOData[Person]) -> Person:
"""Create a person."""
return data.update_instance(database.get(person_id))
"""Partially update a person."""
return data.update_instance(database[person_id])


app = Litestar(route_handlers=[update_person])
Expand Down
36 changes: 14 additions & 22 deletions docs/examples/middleware/base.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,38 @@
from time import time
from typing import TYPE_CHECKING, Dict
import time
from typing import Dict

from litestar import Litestar, get, websocket
from litestar import Litestar, WebSocket, get, websocket
from litestar.datastructures import MutableScopeHeaders
from litestar.enums import ScopeType
from litestar.middleware import AbstractMiddleware

if TYPE_CHECKING:
from litestar import WebSocket
from litestar.types import Message, Receive, Scope, Send
from litestar.types import Message, Receive, Scope, Send


class MyMiddleware(AbstractMiddleware):
scopes = {ScopeType.HTTP}
exclude = ["first_path", "second_path"]
exclude_opt_key = "exclude_from_middleware"
exclude_opt_key = "exclude_from_my_middleware"

async def __call__(
self,
scope: "Scope",
receive: "Receive",
send: "Send",
) -> None:
start_time = time()
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
start_time = time.monotonic()

async def send_wrapper(message: "Message") -> None:
if message["type"] == "http.response.start":
process_time = time() - start_time
process_time = time.monotonic() - start_time
headers = MutableScopeHeaders.from_message(message=message)
headers["X-Process-Time"] = str(process_time)
await send(message)
await send(message)

await self.app(scope, receive, send_wrapper)


@websocket("/my-websocket")
async def websocket_handler(socket: "WebSocket") -> None:
async def websocket_handler(socket: WebSocket) -> None:
"""
Websocket handler - is excluded because the middleware scopes includes 'ScopeType.HTTP'
"""
await socket.accept()
await socket.send_json({"hello websocket"})
await socket.send_json({"hello": "websocket"})
await socket.close()


Expand All @@ -56,10 +48,10 @@ def second_handler() -> Dict[str, str]:
return {"hello": "second"}


@get("/third_path", exclude_from_middleware=True, sync_to_thread=False)
@get("/third_path", exclude_from_my_middleware=True, sync_to_thread=False)
def third_handler() -> Dict[str, str]:
"""Handler is excluded due to the opt key 'exclude_from_middleware' matching the middleware 'exclude_opt_key'."""
return {"hello": "second"}
"""Handler is excluded due to the opt key 'exclude_from_my_middleware' matching the middleware 'exclude_opt_key'."""
return {"hello": "third"}


@get("/greet", sync_to_thread=False)
Expand Down
Loading
Loading