Skip to content

Commit

Permalink
chore: 🧹 update all deps to their latest versions (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
lucas-labs authored Aug 20, 2024
1 parent fc1363b commit 69c3547
Show file tree
Hide file tree
Showing 16 changed files with 464 additions and 436 deletions.
24 changes: 8 additions & 16 deletions .ruff.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
line-length = 100
indent-width = 4
output-format = "text"
output-format = "full"

select = ["E", "F", "Q", "I", "ANN", "ASYNC", "W", "S", "A"]
# [format]
# quote-style = "preserve"

[lint]
select = ["E", "F", "Q", "I", "ANN", "ASYNC", "W", "S", "A"]
ignore = [
"A", # flake8-builtins https://beta.ruff.rs/docs/settings/#flake8-builtins
"ANN101", # missing-type-self https://beta.ruff.rs/docs/rules/missing-type-self/
Expand All @@ -14,28 +17,17 @@ ignore = [
# "F401" # unused-import https://beta.ruff.rs/docs/rules/unused-import/
]

extend-exclude = [
".patches"
]


# [format]
# preserve is not supported yet, but there's a PR in the works
# https://github.com/astral-sh/ruff/pull/8822
# quote-style = "preservev"


[flake8-quotes]
[lint.flake8-quotes]
docstring-quotes = "double"
inline-quotes = "single"
multiline-quotes = "single"


[flake8-annotations]
[lint.flake8-annotations]
mypy-init-return = true


[extend-per-file-ignores]
[lint.extend-per-file-ignores]
# ignore in tests:
# S101 (use of assert)
# ANN001 (missing function argument type annotation)
Expand Down
5 changes: 1 addition & 4 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,5 @@
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"python.analysis.typeCheckingMode": "basic",
"python.analysis.autoImportCompletions": true,
"python.analysis.exclude": [
"**/.patches/**/",
]
"python.analysis.autoImportCompletions": true
}
22 changes: 22 additions & 0 deletions example/app/modules/todo/controllers/root_controller.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from typing import Annotated, List, TypeAlias, cast

from fastapi import Path

# from loguru import logger
from pest.decorators.controller import controller
from pest.decorators.handler import get

from ..models.todo import ReadTodoModel
from ..services.todo_service import TodoService

IdPathParam: TypeAlias = Annotated[int, Path(description='''A todo's **unique** identifier''')]


@controller('', tags=['Root'])
class RootController:
todos: TodoService # 💉 automatically injected

@get('/')
def get_all_todos(self) -> List[ReadTodoModel]:
# logger.info('Getting all todos')
return cast(List[ReadTodoModel], self.todos.get_all())
3 changes: 2 additions & 1 deletion example/app/modules/todo/module.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from pest.decorators.module import module

from .controllers.root_controller import RootController
from .controllers.todo_controller import TodoController
from .services.todo_service import TodoService


@module(
controllers=[TodoController],
controllers=[TodoController, RootController],
providers=[TodoService],
exports=[TodoService],
)
Expand Down
20 changes: 13 additions & 7 deletions pest/core/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
Tuple,
Type,
Union,
cast,
)

try:
Expand All @@ -20,7 +21,6 @@
from fastapi import FastAPI, Response, routing
from fastapi.datastructures import Default, DefaultPlaceholder
from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError
from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware
from fastapi.params import Depends
from fastapi.responses import JSONResponse
from fastapi.types import DecoratedCallable, IncEx
Expand All @@ -41,6 +41,7 @@
from ..metadata.types.module_meta import InjectionToken
from ..middleware.base import (
PestBaseHTTPMiddleware,
PestMiddlwareCallback,
)
from ..middleware.di import di_scope_middleware
from ..middleware.types import MiddlewareDef
Expand All @@ -65,9 +66,15 @@ def __init__(
[]
if middleware is None
else [
middleware
if isinstance(middleware, Middleware)
else Middleware(PestBaseHTTPMiddleware, dispatch=middleware, parent_module=module)
(
middleware
if isinstance(middleware, Middleware)
else Middleware(
PestBaseHTTPMiddleware,
dispatch=cast(PestMiddlwareCallback, middleware),
parent_module=module,
)
)
for middleware in middleware
]
)
Expand Down Expand Up @@ -259,10 +266,9 @@ def build_middleware_stack(self) -> ASGIApp:
+ di_scope_mw # <--- this is the only difference
+ self.user_middleware
+ [Middleware(ExceptionMiddleware, handlers=exception_handlers, debug=debug)]
+ [Middleware(AsyncExitStackMiddleware)]
)

app = self.router
for cls, options in reversed(middleware):
app = cls(app=app, **options)
for cls, args, kwargs in reversed(middleware):
app = cls(app=app, *args, **kwargs)
return app
4 changes: 1 addition & 3 deletions pest/core/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,7 @@ def _get_pest_injection(parameter: Parameter) -> Union[List[_Inject], None]:
token = (
parameter.default.token
if parameter.default.token is not None
else parameter.annotation
if parameter.annotation is not Parameter.empty
else None
else parameter.annotation if parameter.annotation is not Parameter.empty else None
)
annotations = (token, inject)
else:
Expand Down
12 changes: 6 additions & 6 deletions pest/core/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,17 +164,17 @@ def register(self, provider: Provider) -> None:
self.container.bind_types(
provider.provide,
provider.use_class,
life_style=provider.scope
if provider.scope is not None
else ServiceLifeStyle.TRANSIENT,
life_style=(
provider.scope if provider.scope is not None else ServiceLifeStyle.TRANSIENT
),
)
elif isinstance(provider, FactoryProvider):
self.container.register_factory(
factory=provider.use_factory,
return_type=provider.provide,
life_style=provider.scope
if provider.scope is not None
else ServiceLifeStyle.TRANSIENT,
life_style=(
provider.scope if provider.scope is not None else ServiceLifeStyle.TRANSIENT
),
)
elif isinstance(provider, ValueProvider):
self.container.add_instance(
Expand Down
9 changes: 2 additions & 7 deletions pest/core/types/fastapi_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,7 @@
Union,
)

try:
from typing import Self
except ImportError:
from typing_extensions import Self

from fastapi import Request, Response
from fastapi import FastAPI, Request, Response
from fastapi.params import Depends
from fastapi.routing import APIRouter
from starlette.routing import BaseRoute
Expand Down Expand Up @@ -45,7 +40,7 @@ class FastAPIParams(TypedDict, total=False):
]
on_startup: Sequence[Callable[[], Any]]
on_shutdown: Sequence[Callable[[], Any]]
lifespan: Lifespan[Self]
lifespan: Lifespan[FastAPI]
terms_of_service: str
contact: Dict[str, Union[str, Any]]
license_info: Dict[str, Union[str, Any]]
Expand Down
2 changes: 1 addition & 1 deletion pest/factory/app_creator.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def make_app(
for method in route.methods:
full_route = f'{prefix}{route.path}'

if full_route != '/' and not full_route.endswith('/'):
if full_route == '/' or not full_route.endswith('/'):
log.debug(f'{method: <7} {full_route}')

# add the router
Expand Down
10 changes: 6 additions & 4 deletions pest/metadata/meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,11 @@ def get_meta(


def get_meta_value(
callable: Callable[..., Any], key: str, default: Any = None, *, type: Type[GenericValue] = Any
callable: Callable[..., Any],
key: str,
default: Any = None,
*,
type: Type[GenericValue] = Type[Any],
) -> GenericValue:
"""🐀 ⇝ get pest metadata `value` from a `callable` by `key`"""

Expand Down Expand Up @@ -90,9 +94,7 @@ def inject_metadata(
dict_meta: dict = (
asdict(metadata)
if is_dataclass(metadata) and not isinstance(metadata, type)
else metadata
if isinstance(metadata, dict)
else {}
else metadata if isinstance(metadata, dict) else {}
)
except Exception as e:
if is_dataclass(metadata) and not isinstance(metadata, type):
Expand Down
6 changes: 2 additions & 4 deletions pest/middleware/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,12 @@ async def __call__(
self,
request: Request,
call_next: CallNext,
) -> Response:
...
) -> Response: ...


@runtime_checkable
class PestMiddleware(Protocol):
async def use(self, request: Request, call_next: CallNext) -> Response:
...
async def use(self, request: Request, call_next: CallNext) -> Response: ...

@final
async def __call__(
Expand Down
116 changes: 59 additions & 57 deletions pest/utils/fastapi/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,65 +78,67 @@ def add_api_route(
y viceversa.
"""

if path.endswith('/') and path != '/':
if path.endswith('/'):
path = path[:-1]

alternate_path = path + '/'

super().add_api_route(
path,
endpoint,
response_model=response_model,
status_code=status_code,
tags=tags,
dependencies=dependencies,
summary=summary,
description=description,
response_description=response_description,
responses=responses,
deprecated=deprecated,
methods=methods,
operation_id=operation_id,
response_model_include=response_model_include,
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class,
name=name,
route_class_override=route_class_override,
callbacks=callbacks,
openapi_extra=openapi_extra,
generate_unique_id_function=generate_unique_id_function,
)
if (self.prefix + path) != '':
super().add_api_route(
path,
endpoint,
response_model=response_model,
status_code=status_code,
tags=tags,
dependencies=dependencies,
summary=summary,
description=description,
response_description=response_description,
responses=responses,
deprecated=deprecated,
methods=methods,
operation_id=operation_id,
response_model_include=response_model_include,
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class,
name=name,
route_class_override=route_class_override,
callbacks=callbacks,
openapi_extra=openapi_extra,
generate_unique_id_function=generate_unique_id_function,
)

super().add_api_route(
alternate_path,
endpoint,
response_model=response_model,
status_code=status_code,
tags=tags,
dependencies=dependencies,
summary=summary,
description=description,
response_description=response_description,
responses=responses,
deprecated=deprecated,
methods=methods,
operation_id=operation_id,
response_model_include=response_model_include,
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=False,
response_class=response_class,
name=name,
route_class_override=route_class_override,
callbacks=callbacks,
openapi_extra=openapi_extra,
generate_unique_id_function=generate_unique_id_function,
)
if (self.prefix + alternate_path) != '':
super().add_api_route(
alternate_path,
endpoint,
response_model=response_model,
status_code=status_code,
tags=tags,
dependencies=dependencies,
summary=summary,
description=description,
response_description=response_description,
responses=responses,
deprecated=deprecated,
methods=methods,
operation_id=operation_id,
response_model_include=response_model_include,
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=False,
response_class=response_class,
name=name,
route_class_override=route_class_override,
callbacks=callbacks,
openapi_extra=openapi_extra,
generate_unique_id_function=generate_unique_id_function,
)
Loading

0 comments on commit 69c3547

Please sign in to comment.