Skip to content

Commit

Permalink
fix format and lint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
majsan committed Jan 29, 2024
1 parent 1e61d61 commit eaaf650
Show file tree
Hide file tree
Showing 58 changed files with 177 additions and 325 deletions.
2 changes: 1 addition & 1 deletion karp-backend/src/karp/auth_infrastructure/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def jwt_auth_service_config(self) -> JWTAuthServiceConfig: # noqa: D102
@injector.provider
def jwt_auth_service( # noqa: D102
self, is_resource_protected: LexIsResourceProtected
) -> JWTAuthService:
) -> JWTAuthService:
return JWTAuthService(
pubkey_path=self.pubkey_path, is_resource_protected=is_resource_protected
)
10 changes: 3 additions & 7 deletions karp-backend/src/karp/cliapp/subapps/entries_subapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,7 @@ def validate_entries( # noqa: ANN201, D103
),
resource_id_raw: Optional[str] = typer.Option(None, "--resource_id"),
as_import: bool = typer.Option(False, "--as-import"),
output: Optional[Path] = typer.Option(
None, "--output", "-o", help="file to write to"
),
output: Optional[Path] = typer.Option(None, "--output", "-o", help="file to write to"),
):
"""Validate entries without adding or importing them.
Expand Down Expand Up @@ -221,13 +219,11 @@ def validate_entries( # noqa: ANN201, D103
raise typer.Exit(code=300)

allow_additional_properties = config.get("additionalProperties", True)
schema = entry_schema.create_entry_json_schema(config["fields"],allow_additional_properties)
schema = entry_schema.create_entry_json_schema(config["fields"], allow_additional_properties)

error_code = 0

entries: Iterable[dict] = json_streams.load_from_file(
path, use_stdin_as_default=True
)
entries: Iterable[dict] = json_streams.load_from_file(path, use_stdin_as_default=True)
if as_import:
entries = (import_entry["entry"] for import_entry in entries)
with json_streams.sink_from_file(
Expand Down
2 changes: 1 addition & 1 deletion karp-backend/src/karp/cliapp/subapps/entry_repo_subapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def create(infile: typer.FileBinaryRead, ctx: typer.Context): # noqa: ANN201, D
try:
data = json.load(infile)
except Exception as err: # noqa: BLE001
typer.echo(f"Error reading file '{infile.name}': {str(err)}")
typer.echo(f"Error reading file '{infile.name}': {err!s}")
raise typer.Exit(123) from err
create_entry_repo = CreateEntryRepository.from_dict(
data,
Expand Down
4 changes: 1 addition & 3 deletions karp-backend/src/karp/cliapp/subapps/query_subapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@
def resource( # noqa: ANN201, D103
ctx: typer.Context,
resource_id: str,
output: Optional[Path] = typer.Option(
None, help="Path to write to. Defaults to stdout."
),
output: Optional[Path] = typer.Option(None, help="Path to write to. Defaults to stdout."),
):
search_service = inject_from_ctx(Es6SearchService, ctx)
query_request = search.QueryRequest(resource_ids=[resource_id])
Expand Down
12 changes: 7 additions & 5 deletions karp-backend/src/karp/cliapp/subapps/resource_subapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@
from karp.command_bus import CommandBus
from karp.lex_core.value_objects import UniqueIdStr, unique_id
from karp.lex_core import commands as lex_commands
from karp.lex_infrastructure import SqlGetPublishedResources, SqlGetResources, SqlReadOnlyResourceRepository, \
SqlListEntryRepos
from karp.lex_infrastructure import (
SqlGetPublishedResources,
SqlGetResources,
SqlReadOnlyResourceRepository,
SqlListEntryRepos,
)
from karp.search import commands as search_commands

from karp.cliapp.utility import cli_error_handler, cli_timer
Expand Down Expand Up @@ -179,9 +183,7 @@ def show( # noqa: ANN201, D103
resource = repo.get_by_resource_id(resource_id, version=version)
if not resource:
version_str = version or "latest"
typer.echo(
f"Can't find resource '{resource_id}', version '{version_str}'", err=True
)
typer.echo(f"Can't find resource '{resource_id}', version '{version_str}'", err=True)
raise typer.Exit(3)

typer.echo(tabulate(((key, value) for key, value in resource.dict().items())))
Expand Down
8 changes: 2 additions & 6 deletions karp-backend/src/karp/foundation/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,7 @@ def _increment_version(self): # noqa: ANN202

def _validate_version(self, version: int) -> None:
if version != self.version:
raise ConsistencyError(
f"Entity version mismatch: {version} != {self.version}"
)
raise ConsistencyError(f"Entity version mismatch: {version} != {self.version}")


class TimestampedEntity(Entity): # noqa: D101
Expand All @@ -90,9 +88,7 @@ def __init__( # noqa: D107
) -> None:
super().__init__(id=id, discarded=discarded)
self._last_modified = self._ensure_timestamp(last_modified)
self._last_modified_by = (
"Unknown user" if last_modified_by is None else last_modified_by
)
self._last_modified_by = "Unknown user" if last_modified_by is None else last_modified_by

@property
def last_modified(self): # noqa: ANN201
Expand Down
5 changes: 4 additions & 1 deletion karp-backend/src/karp/foundation/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ class NotFoundError(Exception): # noqa: D100
entity_name: str = "Generic entity"

def __init__( # noqa: D107
self, entity_id, *args, msg: str | None = None # noqa: ANN002
self,
entity_id,
*args,
msg: str | None = None, # noqa: ANN002
) -> None:
msg = msg or f"{self.entity_name} not found. Id: {entity_id}"
super().__init__(msg, *args)
Expand Down
4 changes: 1 addition & 3 deletions karp-backend/src/karp/foundation/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,5 @@ def post(self, event: Event) -> None: # noqa: D102
try:
evt_handler(event)
except Exception as err: # noqa: F841
logger.exception(
"Exception handling event", extra={"karp_event": event}
)
logger.exception("Exception handling event", extra={"karp_event": event})
raise
4 changes: 1 addition & 3 deletions karp-backend/src/karp/karp_v6_api/contrib/matomo.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,7 @@ async def dispatch( # noqa: D102
try:
logger.debug("Making tracking call", extra={"url": tracking_url})
r = http.request("GET", tracking_url)
logger.debug(
"tracking call", extra={"status_code": r.status, "data": r.data}
)
logger.debug("tracking call", extra={"status_code": r.status, "data": r.data})
except urllib3.exceptions.HTTPError:
logger.exception("Error tracking view")
return response
8 changes: 4 additions & 4 deletions karp-backend/src/karp/karp_v6_api/dependencies/auth_deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def get_user( # noqa: D103
extra={"credentials": credentials},
)
return auth_service.authenticate(credentials.scheme, credentials.credentials)
except KarpError:
raise credentials_exception
except TokenError:
raise credentials_exception
except KarpError as err:
raise credentials_exception from err
except TokenError as err:
raise credentials_exception from err
5 changes: 2 additions & 3 deletions karp-backend/src/karp/karp_v6_api/dependencies/lex_deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

from karp.lex.application.repositories import EntryUnitOfWorkCreator


def get_resource_unit_of_work( # noqa: D103
db_session: Session = Depends(get_session),
event_bus: EventBus = Depends(event_deps.get_eventbus),
Expand All @@ -43,9 +44,7 @@ def get_resource_unit_of_work( # noqa: D103

def get_entry_repo_uow( # noqa: D103
db_session: Session = Depends(get_session),
entry_uow_factory: EntryUnitOfWorkCreator = Depends(
inject_from_req(EntryUnitOfWorkCreator)
),
entry_uow_factory: EntryUnitOfWorkCreator = Depends(inject_from_req(EntryUnitOfWorkCreator)),
event_bus: EventBus = Depends(event_deps.get_eventbus),
) -> EntryUowRepositoryUnitOfWork:
return SqlEntryUowRepositoryUnitOfWork(
Expand Down
4 changes: 1 addition & 3 deletions karp-backend/src/karp/karp_v6_api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,9 +230,7 @@ async def _logging_middleware(request: Request, call_next) -> Response:
access_token=app_context.settings["tracking.matomo.token"],
)
else:
logger.warning(
"Tracking to Matomo is not enabled, please set TRACKING_MATOMO_URL."
)
logger.warning("Tracking to Matomo is not enabled, please set TRACKING_MATOMO_URL.")
app.add_middleware(CorrelationIdMiddleware)

return app
Expand Down
4 changes: 1 addition & 3 deletions karp-backend/src/karp/karp_v6_api/routes/entries_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,7 @@
logger = logging.getLogger(__name__)


@router.get(
"/{resource_id}/{entry_id}/{version}", response_model=EntryDto, tags=["History"]
)
@router.get("/{resource_id}/{entry_id}/{version}", response_model=EntryDto, tags=["History"])
@router.get("/{resource_id}/{entry_id}", response_model=EntryDto, tags=["History"])
def get_history_for_entry( # noqa: ANN201, D103
resource_id: str,
Expand Down
2 changes: 1 addition & 1 deletion karp-backend/src/karp/karp_v6_api/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class BaseModel(pydantic.BaseModel):

class Config: # noqa: D106
alias_generator = alias_generators.to_lower_camel
json_encoders = {ulid.ULID: lambda u: u.str}
json_encoders: typing.ClassVar = {ulid.ULID: lambda u: u.str}

def serialize(self) -> dict:
"""Serialize model to dict."""
Expand Down
4 changes: 1 addition & 3 deletions karp-backend/src/karp/lex/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,7 @@ def import_entries( # noqa: D102
resource_uow: ResourceUnitOfWork,
entry_repo_uow: EntryUowRepositoryUnitOfWork,
) -> CommandHandler[commands.ImportEntries]:
return ImportingEntries(
resource_uow=resource_uow, entry_repo_uow=entry_repo_uow
)
return ImportingEntries(resource_uow=resource_uow, entry_repo_uow=entry_repo_uow)

@injector.provider
def importing_entries_in_chunks( # noqa: D102
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ def get_by_resource_id( # noqa: D102
if resource := self.get_by_resource_id_optional(resource_id, version=version):
return resource
else:
raise self.EntityNotFound(
f"Entity with resource_id='{resource_id}' can't be found."
)
raise self.EntityNotFound(f"Entity with resource_id='{resource_id}' can't be found.")

def get_by_resource_id_optional( # noqa: D102
self, resource_id: str, *, version: Optional[int] = None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,9 +233,7 @@ def execute(self, command: commands.DeleteEntry) -> None: # noqa: D102
uw.commit()


class ExecutingBatchOfEntryCommands(
CommandHandler[commands.ExecuteBatchOfEntryCommands]
):
class ExecutingBatchOfEntryCommands(CommandHandler[commands.ExecuteBatchOfEntryCommands]):
def __init__(self, command_bus: CommandBus) -> None:
self.command_bus = command_bus

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ def execute(self, command: commands.CreateResource) -> ResourceDto: # noqa: D10
)

with self.resource_uow as uow:
existing_resource = uow.repo.get_by_resource_id_optional(
command.resource_id
)
existing_resource = uow.repo.get_by_resource_id_optional(command.resource_id)
if (
existing_resource
and not existing_resource.discarded
Expand Down
2 changes: 1 addition & 1 deletion karp-backend/src/karp/lex/domain/entities/entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def create_entry( # noqa: D103
*,
id: unique_id.UniqueId, # noqa: A002
repo_id: unique_id.UniqueId,
last_modified_by: str = None,
last_modified_by: Optional[str] = None,
message: Optional[str] = None,
last_modified: typing.Optional[float] = None,
) -> Tuple[Entry, list[events.Event]]:
Expand Down
14 changes: 6 additions & 8 deletions karp-backend/src/karp/lex/domain/entities/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def publish( # noqa: D102
user: str,
message: str,
version: int,
timestamp: float = None,
timestamp: Optional[float] = None,
) -> list[events.Event]:
self._update_metadata(timestamp, user, message or "Published", version)
self.is_published = True
Expand Down Expand Up @@ -137,9 +137,7 @@ def set_resource_id( # noqa: D102
timestamp: Optional[float] = None,
message: Optional[str] = None,
) -> list[events.Event]:
self._update_metadata(
timestamp, user, message or "setting resource_id", version
)
self._update_metadata(timestamp, user, message or "setting resource_id", version)
self._resource_id = resource_id
return [
events.ResourceUpdated(
Expand Down Expand Up @@ -227,7 +225,7 @@ def release_with_name(self, name: str): # noqa: ANN201, D102
raise NotImplementedError()

def discard( # noqa: D102
self, *, user: str, message: str, timestamp: float = None
self, *, user: str, message: str, timestamp: Optional[float] = None
) -> list[events.Event]:
self._op = ResourceOp.DELETED
self._message = message or "Entry deleted."
Expand Down Expand Up @@ -382,9 +380,9 @@ def description(self) -> str:
def create_resource( # noqa: D103
config: dict[str, Any],
entry_repo_id: unique_id.UniqueId,
created_by: str = None,
user: str = None,
created_at: float = None,
created_by: Optional[str] = None,
user: Optional[str] = None,
created_at: Optional[float] = None,
id: unique_id.UniqueId = None, # noqa: A002
resource_id: typing.Optional[str] = None,
message: typing.Optional[str] = None,
Expand Down
15 changes: 12 additions & 3 deletions karp-backend/src/karp/lex/domain/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ class EntryNotFound(NotFoundError, LexDomainError): # noqa: D101
entity_name = "Entry"

def __init__( # noqa: D107
self, *args, entity_id=None, **kwargs # noqa: ANN002, ANN003
self,
*args,
entity_id=None,
**kwargs, # noqa: ANN002, ANN003
) -> None:
NotFoundError.__init__(self, entity_id, *args)
LexDomainError.__init__(self, **kwargs)
Expand All @@ -33,7 +36,10 @@ class EntryRepoNotFound(NotFoundError, LexDomainError): # noqa: D101
entity_name = "EntryRepository"

def __init__( # noqa: D107
self, entity_id, *args, **kwargs # noqa: ANN002, ANN003
self,
entity_id,
*args,
**kwargs, # noqa: ANN002, ANN003
) -> None:
NotFoundError.__init__(self, entity_id, *args)
LexDomainError.__init__(self, entity_id, *args, **kwargs)
Expand All @@ -43,7 +49,10 @@ class ResourceNotFound(NotFoundError, LexDomainError): # noqa: D101
entity_name = "Resource"

def __init__( # noqa: D107
self, entity_id, *args, **kwargs # noqa: ANN002, ANN003
self,
entity_id,
*args,
**kwargs, # noqa: ANN002, ANN003
) -> None:
NotFoundError.__init__(self, entity_id, *args)
LexDomainError.__init__(self, entity_id, *args, **kwargs)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ def validate_entry(self, json_obj: dict[str, Any]) -> dict[str, Any]:
try:
self._compiled_schema(json_obj)
except fastjsonschema.JsonSchemaException as e:
logger.warning(
"Entry not valid", extra={"entry": json_obj, "error_message": str(e)}
)
logger.warning("Entry not valid", extra={"entry": json_obj, "error_message": str(e)})
raise errors.InvalidEntry() from e
return json_obj

Expand Down Expand Up @@ -74,7 +72,6 @@ def recursive_field(
parent_field_name: str,
parent_field_def: dict[str, Any],
) -> None:

if parent_field_def["type"] != "object":
# TODO this will not work when we have user defined types, s.a. saldoid
schema_type = json_schema_type(parent_field_def["type"])
Expand Down
6 changes: 2 additions & 4 deletions karp-backend/src/karp/lex_infrastructure/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,9 @@ def resources_uow( # noqa: D102

@injector.provider
def entry_uow_creator( # noqa: D102
self,
session_factory: sessionmaker,
event_bus: EventBus
self, session_factory: sessionmaker, event_bus: EventBus
) -> EntryUnitOfWorkCreator: # noqa: D102
return SqlEntryUowCreator(session = session_factory(), event_bus = event_bus)
return SqlEntryUowCreator(session=session_factory(), event_bus=event_bus)


class GenericLexInfrastructure(injector.Module): # noqa: D101
Expand Down
Loading

0 comments on commit eaaf650

Please sign in to comment.