chores: updates-and-linters (#1868)

* switch to ruff

* add ruff

* run ruff --fix

* update ruff

* resolve ruff errors

* drop isort from CI

* fix decorator order
This commit is contained in:
Hayden
2022-11-30 20:20:28 -09:00
committed by GitHub
parent fd0e02a5c6
commit 82dc586bac
62 changed files with 362 additions and 536 deletions

View File

@@ -5,7 +5,7 @@ See their repository for details -> https://github.com/dmontagu/fastapi-utils
"""
import inspect
from collections.abc import Callable
from typing import Any, TypeVar, Union, cast, get_type_hints
from typing import Any, TypeVar, cast, get_type_hints
from fastapi import APIRouter, Depends
from fastapi.routing import APIRoute
@@ -92,8 +92,8 @@ def _init_cbv(cls: type[Any], instance: Any = None) -> None:
else:
old_init(self, *args, **kwargs)
setattr(cls, "__signature__", new_signature)
setattr(cls, "__init__", new_init)
cls.__signature__ = new_signature
cls.__init__ = new_init
setattr(cls, CBV_CLASS_KEY, True)
for name in private_attributes:
@@ -122,7 +122,7 @@ def _register_endpoints(router: APIRouter, cls: type[Any], *urls: str) -> None:
}
prefix_length = len(router.prefix)
routes_to_append: list[tuple[int, Union[Route, WebSocketRoute]]] = []
routes_to_append: list[tuple[int, Route | WebSocketRoute]] = []
for _, func in function_members:
index_route = numbered_routes_by_endpoint.get(func)
@@ -177,7 +177,7 @@ def _allocate_routes_by_method_name(router: APIRouter, url: str, function_member
api_resource(func)
def _update_cbv_route_endpoint_signature(cls: type[Any], route: Union[Route, WebSocketRoute]) -> None:
def _update_cbv_route_endpoint_signature(cls: type[Any], route: Route | WebSocketRoute) -> None:
"""
Fixes the endpoint signature for a cbv route to ensure FastAPI performs dependency injection properly.
"""
@@ -191,4 +191,4 @@ def _update_cbv_route_endpoint_signature(cls: type[Any], route: Union[Route, Web
]
new_signature = old_signature.replace(parameters=new_parameters)
setattr(route.endpoint, "__signature__", new_signature)
route.endpoint.__signature__ = new_signature

View File

@@ -3,7 +3,6 @@ import json
from collections.abc import Callable
from enum import Enum
from json.decoder import JSONDecodeError
from typing import Optional, Union
from fastapi import APIRouter, Depends, Request, Response
from fastapi.routing import APIRoute
@@ -14,14 +13,14 @@ from mealie.core.dependencies import get_admin_user, get_current_user
class AdminAPIRouter(APIRouter):
"""Router for functions to be protected behind admin authentication"""
def __init__(self, tags: Optional[list[Union[str, Enum]]] = None, prefix: str = "", **kwargs):
def __init__(self, tags: list[str | Enum] | None = None, prefix: str = "", **kwargs):
super().__init__(tags=tags, prefix=prefix, dependencies=[Depends(get_admin_user)], **kwargs)
class UserAPIRouter(APIRouter):
"""Router for functions to be protected behind user authentication"""
def __init__(self, tags: Optional[list[Union[str, Enum]]] = None, prefix: str = "", **kwargs):
def __init__(self, tags: list[str | Enum] | None = None, prefix: str = "", **kwargs):
super().__init__(tags=tags, prefix=prefix, dependencies=[Depends(get_current_user)], **kwargs)

View File

@@ -1,5 +1,4 @@
from datetime import timedelta
from typing import Optional
from fastapi import APIRouter, Depends, Form, status
from fastapi.exceptions import HTTPException
@@ -27,8 +26,8 @@ class CustomOAuth2Form(OAuth2PasswordRequestForm):
password: str = Form(...),
remember_me: bool = Form(False),
scope: str = Form(""),
client_id: Optional[str] = Form(None),
client_secret: Optional[str] = Form(None),
client_id: str | None = Form(None),
client_secret: str | None = Form(None),
):
self.grant_type = grant_type
self.username = username

View File

@@ -1,10 +1,8 @@
from functools import cached_property
from typing import Type
from fastapi import APIRouter, Depends, HTTPException
from pydantic import UUID4
from mealie.core.exceptions import mealie_registered_exceptions
from mealie.routes._base.base_controllers import BaseUserController
from mealie.routes._base.controller import controller
from mealie.routes._base.mixins import HttpRepo

View File

@@ -1,6 +1,5 @@
from datetime import date
from functools import cached_property
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException
@@ -84,15 +83,17 @@ class GroupMealplanController(BaseUserController):
return self.mixins.create_one(
SavePlanEntry(date=data.date, entry_type=data.entry_type, recipe_id=recipe.id, group_id=self.group_id)
)
except IndexError:
raise HTTPException(status_code=404, detail=ErrorResponse.respond(message="No recipes match your rules"))
except IndexError as e:
raise HTTPException(
status_code=404, detail=ErrorResponse.respond(message="No recipes match your rules")
) from e
@router.get("", response_model=PlanEntryPagination)
def get_all(
self,
q: PaginationQuery = Depends(PaginationQuery),
start_date: Optional[date] = None,
end_date: Optional[date] = None,
start_date: date | None = None,
end_date: date | None = None,
):
# merge start and end dates into pagination query only if either is provided
if start_date or end_date:

View File

@@ -45,7 +45,7 @@ class GroupMigrationController(BaseUserController):
migrator: BaseMigrator
match migration_type:
match migration_type: # noqa match not supported by ruff
case SupportedMigrations.chowdown:
migrator = ChowdownMigrator(**args)
case SupportedMigrations.mealie_alpha:

View File

@@ -41,5 +41,5 @@ async def get_recipe_asset(recipe_id: UUID4, file_name: str):
try:
return FileResponse(file)
except Exception:
raise HTTPException(status.HTTP_404_NOT_FOUND)
except Exception as e:
raise HTTPException(status.HTTP_404_NOT_FOUND) from e

View File

@@ -140,7 +140,7 @@ router = UserAPIRouter(prefix="/recipes", tags=["Recipe: CRUD"], route_class=Mea
@controller(router)
class RecipeController(BaseRecipeController):
def handle_exceptions(self, ex: Exception) -> None:
match type(ex):
match type(ex): # noqa match statement not supported
case exceptions.PermissionDenied:
self.logger.error("Permission Denied on recipe controller action")
raise HTTPException(status_code=403, detail=ErrorResponse.respond(message="Permission Denied"))