Skip to content

Commit

Permalink
🚨 Fix formatting issues in code
Browse files Browse the repository at this point in the history
  • Loading branch information
Samuel Guillemet committed Mar 25, 2024
1 parent 479f0e5 commit b1fe6d3
Show file tree
Hide file tree
Showing 92 changed files with 545 additions and 942 deletions.
4 changes: 1 addition & 3 deletions backend/alembic/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,7 @@ def get_url() -> str:


if get_url().startswith("sqlite"):
raise ValueError(
"SQLite is not supported by this migration script, use app/command.py migrate instead."
)
raise ValueError("SQLite is not supported by this migration script, use app/command.py migrate instead.")

if get_url().startswith("postgresql"):
logging.getLogger("alembic.ddl.postgresql").setLevel(logging.WARNING)
Expand Down
6 changes: 2 additions & 4 deletions backend/app/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,15 +114,13 @@
help="SQL command",
)

PROMPT_MESSAGE = (
"Are you sure you want to reset the database, this will delete all data? [y/N] "
)
PROMPT_MESSAGE = "Are you sure you want to reset the database, this will delete all data? [y/N] "


async def main(command: str) -> None:
args = parser.parse_args()

logger.info(f"Running command: {command}")
logger.info("Running command: %s", command)

# OpenAPI schema generation is a special case
# because it doesn't require a database connection
Expand Down
4 changes: 1 addition & 3 deletions backend/app/commands/dump_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ async def dump_db(output_file: str) -> None:
async with get_db.get_session() as session:
for table in tables:
data[table.name] = {}
data[table.name]["columns"] = [
column.name for column in inspect(table).columns
]
data[table.name]["columns"] = [column.name for column in inspect(table).columns]
data[table.name]["data"] = []
for row in await session.execute(table.select()):
data[table.name]["data"].append(row.tuple()._asdict())
Expand Down
2 changes: 1 addition & 1 deletion backend/app/commands/execute_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@


async def execute_sql_command(command: str) -> None:
logger.info(f"Executing SQL command, {command}")
logger.info("Executing SQL command, %s", command)
async with get_db.get_session() as session:
result = await session.execute(text(command))
logger.info(result.all())
13 changes: 3 additions & 10 deletions backend/app/commands/init_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from app.crud.crud_out_of_stock_item import out_of_stock_item as out_of_stock_items
from app.crud.crud_treasury import treasury as treasuries
from app.dependencies import get_db
from app.models.account import Account
from app.schemas import account as account_schema
from app.schemas import out_of_stock_item as out_of_stock_item_schema
from app.schemas import treasury as treasury_schema
Expand All @@ -33,7 +32,7 @@ async def init_db() -> None:
)
logger.info("Treasury created")
# Create account
await accounts.create(
created_account = await accounts.create(
db=session,
obj_in=account_schema.AccountCreate(
username=settings.BASE_ACCOUNT_USERNAME,
Expand All @@ -44,20 +43,14 @@ async def init_db() -> None:
),
)
logger.info("Base account created")
# Activate account
db_obj: Account | None = await accounts.read(
db=session, id=1
) # First account to be created
assert db_obj is not None

updated_account = account_schema.AccountUpdate(
**account_schema.Account.model_validate(db_obj).model_dump()
**account_schema.Account.model_validate(created_account).model_dump(),
)
updated_account.is_active = True
updated_account.scope = SecurityScopes.PRESIDENT
await accounts.update(
db=session,
db_obj=db_obj,
db_obj=created_account,
obj_in=updated_account,
)
logger.info("Base account activated")
Expand Down
20 changes: 9 additions & 11 deletions backend/app/commands/load_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
async def load_db(input_file: str) -> None:
logger.info("Loading dump data")

with open(input_file, "r", encoding="utf-8") as f:
with open(input_file, encoding="utf-8") as f:
data = json.load(f)

async with get_db.get_session() as session:
Expand All @@ -28,7 +28,7 @@ async def load_db(input_file: str) -> None:
for table in reversed(tables):
table_name = table.name
if table_name not in data:
logger.error(f"Table {table_name} not in dump file")
logger.error("Table %s not in dump file", table_name)
continue
table_data = data[table_name]
columns = table_data["columns"]
Expand All @@ -37,7 +37,8 @@ async def load_db(input_file: str) -> None:
# Verify that the columns in the dump file match the columns in the table
if columns != [column.name for column in inspect(table).columns]:
logger.error(
f"Columns in dump file do not match columns in table {table_name}"
"Columns in dump file do not match columns in table %s",
table_name,
)
continue
tables_to_load.append((table, rows))
Expand All @@ -47,16 +48,13 @@ async def load_db(input_file: str) -> None:
await session.execute(table.delete())

for table, rows in reversed(tables_to_load):
logger.info(f"Loading data for table {table.name}")
logger.info("Loading data for table %s", table.name)
for row in rows:
# Convert datetime strings to datetime objects
for column in table.columns:
if (
isinstance(row[column.name], str)
and column.type.python_type == datetime.datetime
):
if isinstance(row[column.name], str) and column.type.python_type == datetime.datetime:
row[column.name] = datetime.datetime.fromisoformat(
row[column.name]
row[column.name],
)
await session.execute(table.insert().values(**row))

Expand All @@ -68,8 +66,8 @@ async def load_db(input_file: str) -> None:
await session.execute(
text(
f"SELECT setval(pg_get_serial_sequence('{table.name}', '{pk_name}'), "
f"coalesce(max({pk_name}), 1)) FROM {table.name}"
)
f"coalesce(max({pk_name}), 1)) FROM {table.name}",
),
)

await session.commit()
Expand Down
5 changes: 3 additions & 2 deletions backend/app/commands/open_api.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
import logging
from pathlib import Path

from app.main import app

Expand All @@ -10,7 +11,7 @@ def open_api(output: str):
"""
Generate OpenAPI schema.
"""
with open(output, "w", encoding="utf-8") as f:
logger.info(f"Writing OpenAPI schema to {output}")
with Path(output).open("w", encoding="utf-8") as f:
logger.info("Writing OpenAPI schema to %s", output)
text: str = json.dumps(app.openapi(), indent=2)
f.write(text)
3 changes: 2 additions & 1 deletion backend/app/core/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ def check_scopes(security_scopes: SecurityScopes, token_scopes: list[str]) -> bo
required_scopes = security_scopes.scopes
# Get the higher scope in `token_scopes`
token_scope = sorted(
token_scopes, key=lambda scope: SecurityScopesHierarchy[scope].value
token_scopes,
key=lambda scope: SecurityScopesHierarchy[scope].value,
)[-1]
# Check if the token scopes are sufficient to access the endpoint
return all(scope in scopes_hierarchy[token_scope] for scope in required_scopes)
27 changes: 8 additions & 19 deletions backend/app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,14 +150,8 @@ class ConfigDevelopment(Settings):
REPOSITORY_NAME: str = "test_repository_name"
REPOSITORY_OWNER: str = "test_repository_owner"

POSTGRES_DATABASE_URI: ClassVar[
str
] = "postgresql+asyncpg://{user}:{password}@{host}:{port}/{db}".format(
user=POSTGRES_USER,
password=POSTGRES_PASSWORD,
host=POSTGRES_HOST,
port=POSTGRES_PORT,
db=POSTGRES_DB,
POSTGRES_DATABASE_URI: ClassVar[str] = (
f"postgresql+asyncpg://{POSTGRES_USER}:{POSTGRES_PASSWORD}@{POSTGRES_HOST}:{POSTGRES_PORT}/{POSTGRES_DB}"
)
SQLITE_DATABASE_URI: ClassVar[str] = "sqlite+aiosqlite:///./clochette.db"

Expand Down Expand Up @@ -209,13 +203,7 @@ class ConfigProduction(Settings):

@property
def DATABASE_URI(self) -> str:
return "postgresql+asyncpg://{user}:{password}@{host}:{port}/{db}".format(
user=self.POSTGRES_USER,
password=self.POSTGRES_PASSWORD,
host=self.POSTGRES_HOST,
port=self.POSTGRES_PORT,
db=self.POSTGRES_DB,
)
return f"postgresql+asyncpg://{self.POSTGRES_USER}:{self.POSTGRES_PASSWORD}@{self.POSTGRES_HOST}:{self.POSTGRES_PORT}/{self.POSTGRES_DB}"


class ConfigTest(Settings):
Expand Down Expand Up @@ -258,7 +246,7 @@ def DATABASE_URI(self) -> str:
env = os.getenv("ENVIRONMENT", "development")


@lru_cache()
@lru_cache
def select_settings(_env: Optional[str] = env):
"""
Returns the application settings based on the environment specified.
Expand All @@ -272,17 +260,18 @@ def select_settings(_env: Optional[str] = env):
Returns:
Settings: The application settings.
"""
logger.info(f"Loading settings for environment {_env}")
logger.info("Loading settings for environment %s", _env)
if _env == "development":
return ConfigDevelopment()

if _env == "production":
return ConfigProduction() # type: ignore
return ConfigProduction()

if _env == "test":
return ConfigTest()

raise ValueError(f"Invalid environment {_env}")
msg = f"Invalid environment {_env}"
raise ValueError(msg)


settings = select_settings()
35 changes: 18 additions & 17 deletions backend/app/core/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,32 +27,33 @@ def decorator(func):
if sync_func:

@functools.wraps(
func
func,
) # This is needed to preserve the original function name
def sync_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except exceptions as e:
logger.error(e)
logger.exception(e)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=detail
status_code=status.HTTP_400_BAD_REQUEST,
detail=detail,
) from e

return sync_wrapper
else:

@functools.wraps(
func
) # This is needed to preserve the original function name
async def async_wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except exceptions as e:
logger.error(e)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=detail
) from e

return async_wrapper
@functools.wraps(
func,
) # This is needed to preserve the original function name
async def async_wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except exceptions as e:
logger.exception(e)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=detail,
) from e

return async_wrapper

return decorator
8 changes: 5 additions & 3 deletions backend/app/core/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,16 @@ async def dispatch(self, request: Request, call_next):
or a default error response if an exception is raised.
"""
try:
body: bytes = await request.body()
return await call_next(request)
# An unhanded exception was raised during the processing of the request
except Exception as e:
logger.debug(
f"Exception raised during processing of request {request.method} {request.url}: {e}"
"Exception raised during processing of request %s %s: %s",
request.method,
request.url,
e,
)
# Get the body of the request as bytes
body: bytes = await request.body()
# Create a background task to call the alert backend function with the exception and request details
task = BackgroundTask(
self.alert_backend,
Expand Down
5 changes: 4 additions & 1 deletion backend/app/core/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,10 @@ def create_access_token(*, subject: int, scopes: list[str]) -> str:


def _create_token(
subject: int, scopes: list[str], expires_delta: timedelta, token_type: str
subject: int,
scopes: list[str],
expires_delta: timedelta,
token_type: str,
) -> str:
"""
Create a JWT token with the given subject, expiration delta, and token type.
Expand Down
Loading

0 comments on commit b1fe6d3

Please sign in to comment.