Skip to content

Commit

Permalink
add examples to docs
Browse files Browse the repository at this point in the history
  • Loading branch information
lesnik512 committed May 12, 2024
1 parent 7d38c89 commit d2973c2
Show file tree
Hide file tree
Showing 11 changed files with 152 additions and 146 deletions.
139 changes: 0 additions & 139 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,142 +43,3 @@ async def some_function(
```bash
pip install that-depends
```

## Usage
### DI-container with dependencies:
```python
import dataclasses
import logging
import typing

from that_depends import BaseContainer, providers


logger = logging.getLogger(__name__)


def create_sync_resource() -> typing.Iterator[str]:
logger.debug("Resource initiated")
yield "sync resource"
logger.debug("Resource destructed")


async def create_async_resource() -> typing.AsyncIterator[str]:
logger.debug("Async resource initiated")
yield "async resource"
logger.debug("Async resource destructed")


@dataclasses.dataclass(kw_only=True, slots=True)
class IndependentFactory:
dep1: str
dep2: int


@dataclasses.dataclass(kw_only=True, slots=True)
class SyncDependentFactory:
independent_factory: IndependentFactory
sync_resource: str


@dataclasses.dataclass(kw_only=True, slots=True)
class AsyncDependentFactory:
independent_factory: IndependentFactory
async_resource: str


class DIContainer(BaseContainer):
sync_resource = providers.Resource(create_sync_resource)
async_resource = providers.AsyncResource(create_async_resource)

independent_factory = providers.Factory(IndependentFactory, dep1="text", dep2=123)
sync_dependent_factory = providers.Factory(
SyncDependentFactory,
independent_factory=independent_factory,
sync_resource=sync_resource,
)
async_dependent_factory = providers.Factory(
AsyncDependentFactory,
independent_factory=independent_factory,
async_resource=async_resource,
)

```

### Usage with `Fastapi`:

```python
import contextlib
import typing

import fastapi
from starlette import status
from starlette.testclient import TestClient

from tests import container


@contextlib.asynccontextmanager
async def lifespan_manager(_: fastapi.FastAPI) -> typing.AsyncIterator[None]:
yield
await container.DIContainer.tear_down()


app = fastapi.FastAPI(lifespan=lifespan_manager)


@app.get("/")
async def read_root(
sync_dependency: typing.Annotated[
container.AsyncDependentFactory,
fastapi.Depends(container.DIContainer.async_dependent_factory),
],
) -> str:
return sync_dependency.async_resource


client = TestClient(app)

response = client.get("/")
assert response.status_code == status.HTTP_200_OK
assert response.json() == "async resource"

```

### Usage with `Litestar`:
```python
import typing
import fastapi
import contextlib
from litestar import Litestar, get
from litestar.di import Provide
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient

from tests import container


@get("/")
async def index(injected: str) -> str:
return injected


@contextlib.asynccontextmanager
async def lifespan_manager(_: fastapi.FastAPI) -> typing.AsyncIterator[None]:
yield
await container.DIContainer.tear_down()


app = Litestar(
route_handlers=[index],
dependencies={"injected": Provide(container.DIContainer.async_resource)},
lifespan=[lifespan_manager],
)


def test_litestar_di() -> None:
with (TestClient(app=app) as client):
response = client.get("/")
assert response.status_code == HTTP_200_OK, response.text
assert response.text == "async resource"
```
42 changes: 42 additions & 0 deletions docs/examples/fastapi.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Usage with `Fastapi`:

```python
import datetime
import contextlib
import typing

import fastapi
from starlette import status
from starlette.testclient import TestClient

from tests import container


@contextlib.asynccontextmanager
async def lifespan_manager(_: fastapi.FastAPI) -> typing.AsyncIterator[None]:
try:
yield
finally:
await container.DIContainer.tear_down()


app = fastapi.FastAPI(lifespan=lifespan_manager)


@app.get("/")
async def read_root(
some_dependency: typing.Annotated[
container.DependentFactory,
fastapi.Depends(container.DIContainer.dependent_factory),
],
) -> datetime.datetime:
return some_dependency.async_resource


client = TestClient(app)

response = client.get("/")
assert response.status_code == status.HTTP_200_OK
assert response.json() == "async resource"

```
55 changes: 55 additions & 0 deletions docs/examples/ioc_container.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# IOC-container with dependencies

```python
import dataclasses
import logging
import typing

from that_depends import BaseContainer, providers


logger = logging.getLogger(__name__)


def create_sync_resource() -> typing.Iterator[str]:
logger.debug("Resource initiated")
try:
yield "sync resource"
finally:
logger.debug("Resource destructed")


async def create_async_resource() -> typing.AsyncIterator[str]:
logger.debug("Async resource initiated")
try:
yield "async resource"
finally:
logger.debug("Async resource destructed")


@dataclasses.dataclass(kw_only=True, slots=True)
class IndependentFactory:
dep1: str
dep2: int


@dataclasses.dataclass(kw_only=True, slots=True)
class DependentFactory:
independent_factory: IndependentFactory
sync_resource: str
async_resource: str


class DIContainer(BaseContainer):
sync_resource = providers.Resource(create_sync_resource)
async_resource = providers.AsyncResource(create_async_resource)

independent_factory = providers.Factory(IndependentFactory, dep1="text", dep2=123)
dependent_factory = providers.Factory(
DependentFactory,
independent_factory=independent_factory,
sync_resource=sync_resource,
async_resource=async_resource,
)

```
40 changes: 40 additions & 0 deletions docs/examples/litestar.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Usage with `Litestar`:

```python
import typing
import fastapi
import contextlib
from litestar import Litestar, get
from litestar.di import Provide
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient

from tests import container


@get("/")
async def index(injected: str) -> str:
return injected


@contextlib.asynccontextmanager
async def lifespan_manager(_: fastapi.FastAPI) -> typing.AsyncIterator[None]:
try:
yield
finally:
await container.DIContainer.tear_down()


app = Litestar(
route_handlers=[index],
dependencies={"injected": Provide(container.DIContainer.async_resource)},
lifespan=[lifespan_manager],
)


def test_litestar_di() -> None:
with (TestClient(app=app) as client):
response = client.get("/")
assert response.status_code == HTTP_200_OK, response.text
assert response.text == "async resource"
```
10 changes: 9 additions & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@
```

```{eval-rst}
.. toctree::
:maxdepth: 1
:caption: Examples
examples/ioc_container
examples/fastapi
examples/litestar
.. toctree::
:maxdepth: 1
:caption: Providers
Expand All @@ -12,4 +20,4 @@
providers/factory
providers/async-factory
providers/list
```
```
2 changes: 1 addition & 1 deletion docs/providers/async-factory.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
### AsyncFactory
# AsyncFactory
- Initialized on every call, as `Factory`.
- Async function is required.
```python
Expand Down
2 changes: 1 addition & 1 deletion docs/providers/async-resource.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
### AsyncResource
# AsyncResource
- Same as `Resource` but async generator function is required.
```python
import typing
Expand Down
2 changes: 1 addition & 1 deletion docs/providers/factory.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
### Factory
# Factory
- Initialized on every call.
- Class or simple function is allowed.
```python
Expand Down
2 changes: 1 addition & 1 deletion docs/providers/list.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
### List
# List
- List provider contains other providers.
- Resolves into list of dependencies.

Expand Down
2 changes: 1 addition & 1 deletion docs/providers/resource.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
### Resource
# Resource
- Resource initialized only once and have teardown logic.
- Generator function is required.
```python
Expand Down
2 changes: 1 addition & 1 deletion docs/providers/singleton.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
### Singleton
# Singleton
- Initialized only once, but without teardown logic.
- Class or simple function is allowed.
```python
Expand Down

0 comments on commit d2973c2

Please sign in to comment.