Skip to content

Commit

Permalink
Merge pull request #33 from bobokun/develop
Browse files Browse the repository at this point in the history
0.1.5
  • Loading branch information
bobokun authored Oct 4, 2024
2 parents a26e3c4 + 9f7f545 commit 31d77bf
Show file tree
Hide file tree
Showing 9 changed files with 60 additions and 7 deletions.
7 changes: 6 additions & 1 deletion CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
# New Updates
- Updated actualpy to 0.4.0
- Updated actualpy to 0.6.0

# Bug fixes
- Better error handling exception logging
- New config option for setting log level
- Allow for flexibility not having the trailing slash for /transactions endpoint
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.1.4
0.1.5
3 changes: 2 additions & 1 deletion api/transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
router = APIRouter()


@router.post("/", dependencies=[Depends(get_api_key)])
@router.post("/transactions", dependencies=[Depends(get_api_key)])
@router.post("/transactions/", dependencies=[Depends(get_api_key)])
def add_transactions(transactions: Union[Transaction, List[Transaction]]):
try:
if isinstance(transactions, Transaction):
Expand Down
1 change: 1 addition & 0 deletions config/config.yml.sample
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ account_mappings:
savings: "8AF657D4-4811-42C7-8272-E299A8DAC43A"
checking: "B2F7DF53-6A9C-42CF-B091-9129A3A9B528"
credit_card: "C3D8F25A-9C7D-4C9B-8589-8A3790C03B2D"
log_level: INFO
1 change: 1 addition & 0 deletions core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class Settings(BaseSettings):
actual_default_account_id: str
actual_backup_payee: str
account_mappings: Dict[str, str]
log_level: str = "INFO"

class Config:
env_file = ".env"
Expand Down
14 changes: 13 additions & 1 deletion core/logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@
from logging.handlers import RotatingFileHandler

from core.config import config_path
from core.config import settings

CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10


class MyLogger:
Expand All @@ -15,19 +24,22 @@ def __new__(cls):

def _setup_logging(self):
self.logger = logging.getLogger("ActualTap")
self.logger.setLevel(logging.INFO)
self._log_level = getattr(logging, settings.log_level.upper())
self.logger.setLevel(self._log_level)

# File handler
log_file_path = config_path.parent.joinpath("ActualTap.log")
file_handler = RotatingFileHandler(log_file_path, maxBytes=1048576, backupCount=5) # 1MB per file, with 5 backups
file_formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
file_handler.setFormatter(file_formatter)
file_handler.setLevel(self._log_level)
self.logger.addHandler(file_handler)

# Console handler
console_handler = logging.StreamHandler()
console_formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
console_handler.setFormatter(console_formatter)
console_handler.setLevel(self._log_level)
self.logger.addHandler(console_handler)

def info(self, msg):
Expand Down
35 changes: 34 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
import json

from fastapi import Depends
from fastapi import FastAPI
from fastapi import HTTPException
from fastapi import Request
from fastapi.exception_handlers import (
http_exception_handler as default_http_exception_handler,
)
from fastapi.exceptions import RequestValidationError
from fastapi.openapi.docs import get_redoc_html
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse

from api import transactions
from core.config import redact_sensitive_settings
from core.logs import MyLogger
from core.security import get_api_key

app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)

app.include_router(transactions.router, prefix="/transactions", tags=["transactions"], dependencies=[Depends(get_api_key)])
app.include_router(transactions.router, prefix="", tags=["transactions"], dependencies=[Depends(get_api_key)])
logger = MyLogger()


@app.get("/", dependencies=[Depends(get_api_key)])
Expand Down Expand Up @@ -41,3 +52,25 @@ async def get_redoc():
@app.get("/openapi.json", include_in_schema=False, dependencies=[Depends(get_api_key)])
async def openapi():
return get_openapi(title="FastAPI", version="1.0.0", routes=app.routes)


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
logger.error(f"Validation error for request {request.method} {request.url}:\n{json.dumps(exc.errors(), indent=2)}")
logger.error(f"Request body: {json.dumps(await request.json(), indent=2)}")

return JSONResponse(
status_code=422,
content={"detail": exc.errors(), "body": await request.json()},
)


@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
# Log the details of the bad request
if exc.status_code == 400 or exc.status_code == 500:
logger.error(f"Validation error for request {request.method} {request.url}:\n{json.dumps(exc.detail, indent=2)}")
logger.error(f"Request body: {json.dumps(await request.json(), indent=2)}")

# Return the default HTTP exception response
return await default_http_exception_handler(request, exc)
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
actualpy==0.5.1
actualpy==0.6.0
fastapi[standard]==0.115.0
pydantic
pydantic-settings
Expand Down
2 changes: 1 addition & 1 deletion services/actual_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def add_transactions(self, transactions: List[Transaction]):
submitted_transactions.append(t)
rs = get_ruleset(actual.session)
rs.run(submitted_transactions)
logger.info("\n" + json.dumps(transaction_info_list, indent=4))
logger.info("\n" + json.dumps(transaction_info_list, indent=2))
actual.commit()
return transaction_info_list

Expand Down

0 comments on commit 31d77bf

Please sign in to comment.