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

docs: move internal code-blocks to docs/examples/**/*.py files to be automatically tested #3445

Open
wants to merge 33 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
21fa663
doc: refactor example in channels, moving code to examples folder
Kumzy Apr 12, 2024
46e3966
doc: refactor example in events, moving code to examples folder
Kumzy Apr 12, 2024
34b2856
doc: refactor example in events, moving code to examples folder + add…
Kumzy Apr 12, 2024
7029897
doc: refactor example in cli, moving code to examples folder
Kumzy Apr 12, 2024
7247861
doc: refactor example in dependency-injection, moving code to example…
Kumzy Apr 14, 2024
f58048a
doc: refactor example in logging, moving code to examples folder
Kumzy Apr 14, 2024
40ab336
doc: refactor example in caching, moving code to examples folder
Kumzy Apr 15, 2024
9dc78c7
doc: refactor example in flask migrations, moving code to examples fo…
Kumzy Apr 18, 2024
39fa913
doc: refactor example in dto, moving code to examples folder
Kumzy Apr 18, 2024
0261d68
doc: refactor example in templating, moving code to examples folder
Kumzy Apr 19, 2024
16f13dc
doc: refactor example in response, moving code to examples folder
Kumzy Apr 19, 2024
9cefe70
doc: refactor example in migrations for fastapi, moving code to examp…
Kumzy Apr 19, 2024
6f50941
doc: refactor example in routing, moving code to examples folder
Kumzy Apr 19, 2024
6b21327
doc: refactor example in dto factory, moving code to examples folder
Kumzy Apr 19, 2024
5f92f2d
doc: refactor example in guards, moving code to examples folder
Kumzy Apr 19, 2024
abf0f0c
docs: fix websockets missing migration to examples folder
Kumzy Apr 20, 2024
ab9bd80
doc: refactor example in applications, moving code to examples folder…
Kumzy Apr 20, 2024
cac4a13
doc: refactor example in debugging, moving code to examples folder
Kumzy Apr 20, 2024
9472d3e
doc: refactor example in index, moving code to examples folder
Kumzy Apr 20, 2024
2c4dba9
doc: refactor example in what's new, moving code to examples folder
Kumzy Apr 20, 2024
14ef9bb
doc: finishing refactor in what's new + refactor middleware + adding …
Kumzy Apr 20, 2024
a78e95d
doc: refactor example in builtin middleware, moving code to examples …
Kumzy Apr 20, 2024
8a700a9
doc: refactor example in testing, moving code to examples folder
Kumzy Apr 20, 2024
c236914
doc: refactor example in openapi, moving code to examples folder
Kumzy Apr 20, 2024
3cb11b2
docs: fix type in filename for openapi
Kumzy Apr 20, 2024
e9a9250
doc: refactor example in routing overview, moving code to examples fo…
Kumzy Apr 20, 2024
8838958
doc: refactor example in creation of middlewares, moving code to exam…
Kumzy Apr 20, 2024
8999ea7
doc: refactor example in middleware creation + docker, moving code to…
Kumzy Apr 21, 2024
8581c60
doc: refactor example in middleware to exclude from endpoints, moving…
Kumzy Apr 21, 2024
356dd3e
doc: refactor example in todo app and open telemetry, moving code to …
Kumzy Apr 21, 2024
be2e0fb
docs: fix indentation level in responses file in response header section
Kumzy Apr 21, 2024
6661e78
Update docs/examples/middleware/builtin/csrf_httpx.py
Kumzy Apr 21, 2024
24637d9
docs: fix python ast, run pre-commit, rebase on latest docs changes
JacobCoffee Apr 27, 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from litestar import get
from litestar.datastructures import State


@get("/")
def handler(state: State) -> None: ...
Empty file.
5 changes: 5 additions & 0 deletions docs/examples/caching/caching_duration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from litestar import get


@get("/cached-path", cache=120) # seconds
def my_cached_handler() -> str: ...
6 changes: 6 additions & 0 deletions docs/examples/caching/caching_forever.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from litestar import get
from litestar.config.response_cache import CACHE_FOREVER


@get("/cached-path", cache=CACHE_FOREVER) # seconds
def my_cached_handler() -> str: ...
9 changes: 9 additions & 0 deletions docs/examples/caching/caching_key_builder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from litestar import Litestar, Request
from litestar.config.cache import ResponseCacheConfig


def key_builder(request: Request) -> str:
return request.url.path + request.headers.get("my-header", "")


app = Litestar([], cache_config=ResponseCacheConfig(key_builder=key_builder))
9 changes: 9 additions & 0 deletions docs/examples/caching/caching_key_builder_specific_route.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from litestar import Request, get


def key_builder(request: Request) -> str:
return request.url.path + request.headers.get("my-header", "")


@get("/cached-path", cache=True, cache_key_builder=key_builder)
def cached_handler() -> str: ...
5 changes: 5 additions & 0 deletions docs/examples/caching/caching_response.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from litestar import get


@get("/cached-path", cache=True)
def my_cached_handler() -> str: ...
6 changes: 6 additions & 0 deletions docs/examples/caching/caching_storage_redis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from litestar.config.cache import ResponseCacheConfig
from litestar.stores.redis import RedisStore

redis_store = RedisStore(url="redis://localhost/", port=6379, db=0)

cache_config = ResponseCacheConfig(store=redis_store)
Empty file.
3 changes: 3 additions & 0 deletions docs/examples/channels/allowing_arbitrary_channels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from litestar.channels import ChannelsPlugin

channels_plugin = ChannelsPlugin(..., arbitrary_channels_allowed=True)
8 changes: 8 additions & 0 deletions docs/examples/channels/backoff_strategy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from litestar.channels import ChannelsPlugin
from litestar.channels.memory import MemoryChannelsBackend

channels = ChannelsPlugin(
backend=MemoryChannelsBackend(),
max_backlog=1000,
backlog_strategy="backoff",
)
8 changes: 8 additions & 0 deletions docs/examples/channels/eviction_strategy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from litestar.channels import ChannelsPlugin
from litestar.channels.memory import MemoryChannelsBackend

channels = ChannelsPlugin(
backend=MemoryChannelsBackend(),
max_backlog=1000,
backlog_strategy="dropleft",
)
3 changes: 3 additions & 0 deletions docs/examples/channels/passing_channels_explicitly.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from litestar.channels import ChannelsPlugin

channels_plugin = ChannelsPlugin(..., channels=["foo", "bar"])
1 change: 1 addition & 0 deletions docs/examples/channels/publish_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
channels.publish({"message": "Hello"}, "general")
2 changes: 2 additions & 0 deletions docs/examples/channels/subscribe_method_context_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
async with channels.start_subscription(["foo", "bar"]) as subscriber:
... # do some stuff here
5 changes: 5 additions & 0 deletions docs/examples/channels/subscribe_method_manually.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
subscriber = await channels.subscribe(["foo", "bar"])
try:
... # do some stuff here
finally:
await channels.unsubscribe(subscriber)
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
async with channels.start_subscription(["foo", "bar"]) as subscriber:
# do some stuff here
await channels.unsubscribe(subscriber, ["foo"])
3 changes: 3 additions & 0 deletions docs/examples/channels/unsubscribe_method_manually.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
subscriber = await channels.subscribe(["foo", "bar"])
# do some stuff here
await channels.unsubscribe(subscriber, ["foo"])
Empty file added docs/examples/cli/__init__.py
Empty file.
7 changes: 7 additions & 0 deletions docs/examples/cli/app_instance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import click

from litestar import Litestar


@click.command()
def my_command(app: Litestar) -> None: ...
9 changes: 9 additions & 0 deletions docs/examples/cli/entry_points.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from setuptools import setup

setup(
name="my-litestar-plugin",
# ..., other setup arguments
entry_points={
"litestar.commands": ["my_command=my_litestar_plugin.cli:main"],
},
)
1 change: 1 addition & 0 deletions docs/examples/cli/info.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
litestar info
1 change: 1 addition & 0 deletions docs/examples/cli/openapi_schema.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
litestar schema openapi --output my-specs.yml
14 changes: 14 additions & 0 deletions docs/examples/cli/plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from click import Group

from litestar import Litestar
from litestar.plugins import CLIPluginProtocol


class CLIPlugin(CLIPluginProtocol):
def on_cli_init(self, cli: Group) -> None:
@cli.command()
def is_debug_mode(app: Litestar):
print(app.debug)


app = Litestar(plugins=[CLIPlugin()])
2 changes: 2 additions & 0 deletions docs/examples/cli/poetry.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[tool.poetry.plugins."litestar.commands"]
my_command = "my_litestar_plugin.cli:main"
1 change: 1 addition & 0 deletions docs/examples/cli/reload_dir.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
litestar run --reload-dir=. --reload-dir=../other-library/src
1 change: 1 addition & 0 deletions docs/examples/cli/reload_dir_multiple_directories.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
LITESTAR_RELOAD_DIRS=.,../other-library/src
1 change: 1 addition & 0 deletions docs/examples/cli/reload_exclude.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
litestar run --reload-exclude="*.py" --reload-exclude="*.yml"
1 change: 1 addition & 0 deletions docs/examples/cli/reload_exclude_multiple_directories.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
LITESTAR_RELOAD_EXCLUDES=*.py,*.yml
1 change: 1 addition & 0 deletions docs/examples/cli/reload_include.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
litestar run --reload-include="*.rst" --reload-include="*.yml"
1 change: 1 addition & 0 deletions docs/examples/cli/reload_include_multiple_directories.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
LITESTAR_RELOAD_INCLUDES=*.rst,*.yml
1 change: 1 addition & 0 deletions docs/examples/cli/routes.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
litestar routes
1 change: 1 addition & 0 deletions docs/examples/cli/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
litestar run
1 change: 1 addition & 0 deletions docs/examples/cli/sessions_clear.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
litestar sessions clear
1 change: 1 addition & 0 deletions docs/examples/cli/sessions_delete.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
litestar sessions delete cc3debc7-1ab6-4dc8-a220-91934a473717
1 change: 1 addition & 0 deletions docs/examples/cli/ssl.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
litestar run --ssl-certfile=certs/cert.pem --ssl-keyfile=certs/key.pem
1 change: 1 addition & 0 deletions docs/examples/cli/ssl_self_signed.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
litestar run --ssl-certfile=certs/cert.pem --ssl-keyfile=certs/key.pem --create-self-signed-cert
1 change: 1 addition & 0 deletions docs/examples/cli/typescript_schema.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
litestar schema typescript
3 changes: 3 additions & 0 deletions docs/examples/cli/typescript_schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export namespace API {
// ...
}
1 change: 1 addition & 0 deletions docs/examples/cli/typescript_schema_namespace.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
litestar schema typescript --namespace MyNamespace
3 changes: 3 additions & 0 deletions docs/examples/cli/typescript_schema_namespace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export namespace MyNamespace {
// ...
}
1 change: 1 addition & 0 deletions docs/examples/cli/typescript_schema_path.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
litestar schema typescript --output my-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from dataclasses import dataclass

from litestar import get
from litestar.dto import DataclassDTO, DTOConfig


@dataclass
class MyType:
some_field: str
another_field: int


class MyDTO(DataclassDTO[MyType]):
config = DTOConfig(exclude={"another_field"})


@get(dto=MyDTO)
async def handler() -> MyType:
return MyType(some_field="some value", another_field=42)
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from dataclasses import dataclass

from litestar.dto import DataclassDTO, DTOConfig


@dataclass
class Foo:
name: str


class FooDTO(DataclassDTO[Foo]):
config = DTOConfig(experimental_codegen_backend=False)
4 changes: 4 additions & 0 deletions docs/examples/data_transfer_objects/enabling_backend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from litestar import Litestar
from litestar.config.app import ExperimentalFeatures

app = Litestar(experimental_features=[ExperimentalFeatures.DTO_CODEGEN])
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from dataclasses import dataclass
from typing import Generic, TypeVar

T = TypeVar("T")


@dataclass
class WithCount(Generic[T]):
count: int
data: List[T]
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from advanced_alchemy.dto import SQLAlchemyDTO

from litestar.dto import DTOConfig


class UserDTO(SQLAlchemyDTO[User]):
config = DTOConfig(exclude={"password", "created_at"})
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from litestar import get


@get("/users", dto=UserDTO, sync_to_thread=False)
def get_users() -> WithCount[User]:
return WithCount(
count=1,
data=[
User(
id=1,
name="Litestar User",
password="xyz",
created_at=datetime.now(),
),
],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
config = DTOConfig(
exclude={
"id",
"address.id",
"address.street",
"pets.0.id",
"pets.0.user_id",
}
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from advanced_alchemy.dto import SQLAlchemyDTO

from litestar.dto import DTOConfig


class UserDTO(SQLAlchemyDTO[User]):
config = DTOConfig(exclude={"password", "created_at"})
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from litestar import get
from litestar.pagination import ClassicPagination


@get("/users", dto=UserDTO, sync_to_thread=False)
def get_users() -> ClassicPagination[User]:
return ClassicPagination(
page_size=10,
total_pages=1,
current_page=1,
items=[
User(
id=1,
name="Litestar User",
password="xyz",
created_at=datetime.now(),
),
],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from advanced_alchemy.dto import SQLAlchemyDTO

from litestar.dto import DTOConfig


class UserDTO(SQLAlchemyDTO[User]):
config = DTOConfig(exclude={"password", "created_at"})
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from litestar import Response, get


@get("/users", dto=UserDTO, sync_to_thread=False)
def get_users() -> Response[User]:
return Response(
content=User(
id=1,
name="Litestar User",
password="xyz",
created_at=datetime.now(),
),
headers={"X-Total-Count": "1"},
)
12 changes: 12 additions & 0 deletions docs/examples/data_transfer_objects/individual_dto.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from dataclasses import dataclass

from litestar.dto import DataclassDTO, DTOConfig


@dataclass
class Foo:
name: str


class FooDTO(DataclassDTO[Foo]):
config = DTOConfig(experimental_codegen_backend=True)
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
app = Litestar(pdb_on_exception=True)
42 changes: 42 additions & 0 deletions docs/examples/dependency_injection/dependency_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from litestar import Controller, Litestar, Router, get
from litestar.di import Provide


async def bool_fn() -> bool: ...


async def dict_fn() -> dict: ...


async def list_fn() -> list: ...


async def int_fn() -> int: ...


class MyController(Controller):
path = "/controller"
# on the controller
dependencies = {"controller_dependency": Provide(list_fn)}

# on the route handler
@get(path="/handler", dependencies={"local_dependency": Provide(int_fn)})
def my_route_handler(
self,
app_dependency: bool,
router_dependency: dict,
controller_dependency: list,
local_dependency: int,
) -> None: ...

# on the router


my_router = Router(
path="/router",
dependencies={"router_dependency": Provide(dict_fn)},
route_handlers=[MyController],
)

# on the app
app = Litestar(route_handlers=[my_router], dependencies={"app_dependency": Provide(bool_fn)})
7 changes: 7 additions & 0 deletions docs/examples/dependency_injection/dependency_connection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from dependencies import CONNECTION, app

from litestar.testing import TestClient

with TestClient(app=app) as client:
print(client.get("/").json()) # {"open": True}
print(CONNECTION) # {"open": False}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from pydantic import UUID4, BaseModel

from litestar import Controller, patch
from litestar.di import Provide


class User(BaseModel):
id: UUID4
name: str


async def retrieve_db_user(user_id: UUID4) -> User: ...


class UserController(Controller):
path = "/user"
dependencies = {"user": Provide(retrieve_db_user)}

@patch(path="/{user_id:uuid}")
async def get_user(self, user: User) -> User: ...
Loading
Loading