py3.11: fix basic linter errors

This commit is contained in:
Jörn-Michael Miehe 2023-10-16 20:06:55 +02:00
parent a2403ade59
commit 6709284ed9
6 changed files with 43 additions and 61 deletions

View file

@ -9,11 +9,8 @@ from logging.config import dictConfig
from pydantic import BaseModel from pydantic import BaseModel
from .app import app
from .settings import SETTINGS from .settings import SETTINGS
__all__ = ["app"]
class LogConfig(BaseModel): class LogConfig(BaseModel):
""" """
@ -22,23 +19,23 @@ class LogConfig(BaseModel):
""" """
# Logging config # Logging config
version = 1 version: int = 1
disable_existing_loggers = False disable_existing_loggers: bool = False
formatters = { formatters: dict = {
"default": { "default": {
"()": "uvicorn.logging.DefaultFormatter", "()": "uvicorn.logging.DefaultFormatter",
"fmt": "%(levelprefix)s [%(asctime)s] %(name)s: %(message)s", "fmt": "%(levelprefix)s [%(asctime)s] %(name)s: %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S", "datefmt": "%Y-%m-%d %H:%M:%S",
}, },
} }
handlers = { handlers: dict = {
"default": { "default": {
"formatter": "default", "formatter": "default",
"class": "logging.StreamHandler", "class": "logging.StreamHandler",
"stream": "ext://sys.stderr", "stream": "ext://sys.stderr",
}, },
} }
loggers = { loggers: dict = {
"ovdashboard_api": { "ovdashboard_api": {
"handlers": ["default"], "handlers": ["default"],
"level": SETTINGS.log_level, "level": SETTINGS.log_level,

View file

@ -30,33 +30,29 @@ app = FastAPI(
redoc_url=SETTINGS.redoc_url, redoc_url=SETTINGS.redoc_url,
) )
app.add_event_handler("startup", webdav_check)
@app.on_event("startup")
async def add_middlewares() -> None:
if SETTINGS.production_mode:
# Mount frontend in production mode
app.mount(
path="/",
app=StaticFiles(
directory=SETTINGS.ui_directory,
html=True,
),
name="frontend",
)
else:
# Allow CORS in debug mode
app.add_middleware(
CORSMiddleware,
allow_origins=[
"*",
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"],
)
app.include_router(v1_router) app.include_router(v1_router)
webdav_check()
if SETTINGS.production_mode:
# Mount frontend in production mode
app.mount(
path="/",
app=StaticFiles(
directory=SETTINGS.ui_directory,
html=True,
),
name="frontend",
)
else:
# Allow CORS in debug mode
app.add_middleware(
CORSMiddleware,
allow_origins=[
"*",
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"],
)

View file

@ -4,10 +4,10 @@ Python representation of the "config.txt" file inside the WebDAV directory.
from io import BytesIO from io import BytesIO
from logging import getLogger from logging import getLogger
from tomllib import loads as toml_loads
from typing import Any from typing import Any
from pydantic import BaseModel from pydantic import BaseModel
from tomli import loads as toml_loads
from tomli_w import dump as toml_dump from tomli_w import dump as toml_dump
from webdav3.exceptions import RemoteResourceNotFound from webdav3.exceptions import RemoteResourceNotFound
@ -119,9 +119,7 @@ class Config(BaseModel):
dav_file = DavFile(SETTINGS.config_path) dav_file = DavFile(SETTINGS.config_path)
try: try:
cfg = cls.parse_obj( cfg = cls.parse_obj(toml_loads(await dav_file.as_string))
toml_loads(await dav_file.as_string)
)
except RemoteResourceNotFound: except RemoteResourceNotFound:
_logger.warning( _logger.warning(

View file

@ -8,12 +8,12 @@ from dataclasses import dataclass
from datetime import datetime, timedelta from datetime import datetime, timedelta
from functools import total_ordering from functools import total_ordering
from logging import getLogger from logging import getLogger
from typing import Iterator from typing import Annotated, Iterator
from cache import AsyncTTL from cache import AsyncTTL
from caldav import Calendar from caldav import Calendar
from caldav.lib.error import ReportError from caldav.lib.error import ReportError
from pydantic import BaseModel, validator from pydantic import AfterValidator, BaseModel
from vobject.base import Component from vobject.base import Component
from .async_helpers import run_in_executor from .async_helpers import run_in_executor
@ -33,6 +33,9 @@ def _string_strip(in_str: str) -> str:
return in_str.strip() return in_str.strip()
StrippedStr = Annotated[str, AfterValidator(lambda s: s.strip())]
@total_ordering @total_ordering
class CalEvent(BaseModel): class CalEvent(BaseModel):
""" """
@ -44,8 +47,8 @@ class CalEvent(BaseModel):
https://icalendar.org/iCalendar-RFC-5545/3-6-1-event-component.html https://icalendar.org/iCalendar-RFC-5545/3-6-1-event-component.html
""" """
summary: str = "" summary: StrippedStr = ""
description: str = "" description: StrippedStr = ""
dtstart: datetime = datetime.utcnow() dtstart: datetime = datetime.utcnow()
dtend: datetime = datetime.utcnow() dtend: datetime = datetime.utcnow()
@ -66,16 +69,6 @@ class CalEvent(BaseModel):
return self.dict() == other.dict() return self.dict() == other.dict()
_validate_summary = validator(
"summary",
allow_reuse=True,
)(_string_strip)
_validate_description = validator(
"description",
allow_reuse=True,
)(_string_strip)
@classmethod @classmethod
def from_vevent(cls, event: Component) -> "CalEvent": def from_vevent(cls, event: Component) -> "CalEvent":
""" """
@ -178,10 +171,7 @@ async def _get_calendar_events(
vobject: Component = event.vobject_instance # type: ignore vobject: Component = event.vobject_instance # type: ignore
yield from vobject.vevent_list yield from vobject.vevent_list
return sorted([ return sorted([CalEvent.from_vevent(vevent) for vevent in await _inner()])
CalEvent.from_vevent(vevent)
for vevent in await _inner()
])
@dataclass(frozen=True) @dataclass(frozen=True)

View file

@ -9,7 +9,7 @@ def main() -> None:
""" """
uvicorn_run( uvicorn_run(
app="ovdashboard_api:app", app="ovdashboard_api.app:app",
host="0.0.0.0", host="0.0.0.0",
port=8000, port=8000,
reload=not SETTINGS.production_mode, reload=not SETTINGS.production_mode,

View file

@ -9,7 +9,8 @@ Pydantic models might have convenience methods attached.
from typing import Any, Optional from typing import Any, Optional
from pydantic import BaseModel, BaseSettings, root_validator from pydantic import BaseModel, root_validator
from pydantic_settings import BaseSettings
class DavSettings(BaseModel): class DavSettings(BaseModel):