Skip to content

Commit 7093cc4

Browse files
committed
✨ Add (module): Additional features for API
1 parent 1c7af5c commit 7093cc4

File tree

13 files changed

+371
-313
lines changed

13 files changed

+371
-313
lines changed

.env.sample.env

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
SERVER_HOST="http://localhost"
2+
BACKEND_CORS_ORIGINS=["http://localhost:5000","http://localhost:3000","http://localhost:8080"]
3+
SERVER_PORT=80
4+
SERVER_RELOAD=True
5+
SERVER_LOG_LEVEL="info"
6+
SERVER_DESCRIPTION="Development environment"
7+
SERVER_URL="http://localhost"
8+
9+
# Postgres
10+
POSTGRES_SCHEME="postgresql+psycopg"
11+
POSTGRES_SERVER="localhost"
12+
POSTGRES_USER="postgres"
13+
POSTGRES_PASSWORD="Password1.-"
14+
POSTGRES_DB="postgres"
15+
POSTGRES_PORT=5432
16+
17+
# OpenAPI Metadata
18+
CONTACT_NAME="Juan Pablo Cadena Aguilar"
19+
CONTACT_URL="https://www.github.com/jpcadena"
20+
CONTACT_EMAIL="[email protected]"

.pre-commit-config.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ repos:
2929
- --keep-runtime-typing
3030

3131
- repo: https://github.com/astral-sh/ruff-pre-commit
32-
rev: v0.4.3
32+
rev: v0.4.6
3333
hooks:
3434
# Run the linter.
3535
- id: ruff
@@ -51,7 +51,7 @@ repos:
5151
args: [ "--config", "pyproject.toml" ]
5252

5353
- repo: https://github.com/astral-sh/ruff-pre-commit
54-
rev: v0.4.3
54+
rev: v0.4.6
5555
hooks:
5656
# Run the formatter.
5757
- id: ruff-format

app/api/api_v1/router/user.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@
1111
from fastapi.params import Path, Query
1212
from pydantic import NonNegativeInt, PositiveInt
1313

14-
from app.config.exceptions import (
14+
from app.config.init_settings import init_setting
15+
from app.core.exceptions import (
1516
DatabaseException,
1617
NotFoundException,
1718
ServiceException,
1819
)
19-
from app.config.init_settings import init_setting
2020
from app.crud.user import UserRepository, get_user_repository
2121
from app.schemas.user import User, UserCreate, UserUpdate, UsersResponse
2222

app/config/settings.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,9 @@ class Settings(BaseSettings):
3535
SERVER_PORT: PositiveInt
3636
SERVER_RELOAD: bool
3737
SERVER_LOG_LEVEL: str
38+
SERVER_DESCRIPTION: str
3839
BACKEND_CORS_ORIGINS: list[AnyHttpUrl] = []
40+
SERVER_URL: AnyHttpUrl
3941

4042
@field_validator("BACKEND_CORS_ORIGINS", mode="before")
4143
def assemble_cors_origins(cls, v: str | list[str]) -> list[str] | str:
@@ -47,7 +49,6 @@ def assemble_cors_origins(cls, v: str | list[str]) -> list[str] | str:
4749
:return: List of Backend CORS origins to be accepted
4850
:rtype: Union[list[str], str]
4951
"""
50-
# pylint: disable=unused-argument,no-self-argument,invalid-name
5152
if isinstance(v, str) and not v.startswith("["):
5253
return [i.strip() for i in v.split(",")]
5354
if isinstance(v, list):

app/core/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"""
2+
Package app-core initialization.
3+
"""
File renamed without changes.

app/core/lifecycle.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""
2+
A module for lifecycle in the app-core package.
3+
"""
4+
5+
import logging
6+
from contextlib import asynccontextmanager
7+
from typing import Any, AsyncGenerator
8+
9+
from fastapi import FastAPI
10+
11+
from app.config.init_settings import get_init_settings
12+
from app.config.settings import get_settings
13+
from app.crud.user import get_user_repository
14+
15+
logger: logging.Logger = logging.getLogger(__name__)
16+
17+
18+
@asynccontextmanager
19+
async def lifespan(application: FastAPI) -> AsyncGenerator[Any, None]:
20+
"""
21+
The lifespan of the application
22+
:param application: The FastAPI application
23+
:type application: FastAPI
24+
:return: An asynchronous generator for the application
25+
:rtype: AsyncGenerator[Any, None]
26+
"""
27+
logger.info("Starting API...")
28+
try:
29+
application.state.settings = get_settings()
30+
application.state.init_settings = get_init_settings()
31+
application.state.user_repository = get_user_repository()
32+
logger.info("Configuration settings loaded.")
33+
yield
34+
except Exception as exc:
35+
logger.error(f"Error during application startup: {exc}")
36+
raise
37+
finally:
38+
logger.info("Application shutdown completed.")

app/config/utils.py renamed to app/core/utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111
from fastapi.routing import APIRoute
1212
from pydantic_extra_types.phone_numbers import PhoneNumber
1313

14-
from app.config.exceptions import ServiceException
1514
from app.config.settings import setting
15+
from app.core.exceptions import ServiceException
1616

1717

1818
def remove_tag_from_operation_id(tag: str, operation_id: str) -> str:
@@ -103,8 +103,8 @@ def custom_openapi(app: FastAPI) -> dict[str, Any]:
103103
routes=app.routes,
104104
servers=[
105105
{
106-
"url": app.state.auth_settings.SERVER_URL,
107-
"description": app.state.auth_settings.SERVER_DESCRIPTION,
106+
"url": app.state.settings.SERVER_URL,
107+
"description": app.state.settings.SERVER_DESCRIPTION,
108108
}
109109
],
110110
contact=app.state.settings.CONTACT,

app/crud/user.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from sqlalchemy.orm import Session
1515
from sqlalchemy.sql import Select
1616

17-
from app.config.exceptions import DatabaseException
17+
from app.core.exceptions import DatabaseException
1818
from app.db.session import get_session
1919
from app.models.user import User
2020
from app.schemas.user import User as UserSchema

app/main.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,14 @@
1414
from app.api.api_v1.api import api_router
1515
from app.config.init_settings import init_setting
1616
from app.config.settings import setting
17-
from app.config.utils import custom_generate_unique_id, custom_openapi
17+
from app.core.lifecycle import lifespan
18+
from app.core.utils import custom_generate_unique_id, custom_openapi
1819

1920
app: FastAPI = FastAPI(
2021
debug=True,
2122
openapi_url=f"{setting.API_V1_STR}{init_setting.OPENAPI_FILE_PATH}",
2223
openapi_tags=init_setting.TAGS_METADATA,
24+
lifespan=lifespan,
2325
generate_unique_id_function=custom_generate_unique_id,
2426
)
2527
app.openapi = partial(custom_openapi, app) # type: ignore

0 commit comments

Comments
 (0)