/
euorik
/
FastAPI-Conda-app
Обзор
Документация
Войти
/
euorik
/
FastAPI-Conda-app
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
fastapi-app/app/main.py
124 строки
5 KB
euorik
Modify FastAPI APP
22 июн 2026, 09:25
22 июн 2026, 09:25
e743827
Код
Авторство
О чём код?
from fastapi import FastAPI, Depends, HTTPException from sqlalchemy import text from sqlalchemy.orm import Session import crud, models, schemas from database import SessionLocal, engine, Base, init_db from datetime import datetime from sqlalchemy.exc import SQLAlchemyError #models.Base.metadata.create_all(bind=engine) #init_db() app = FastAPI(title="Personal Finance API") def get_db(): db = SessionLocal() try: yield db finally: db.close() # Банки @app.post("/banks/", response_model=schemas.BankResponse) def create_bank(bank: schemas.BankCreate, db: Session = Depends(get_db)): return crud.create_bank(db=db, bank=bank) @app.get("/banks/") def read_banks(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): banks = crud.get_banks(db, skip=skip, limit=limit) return banks # Счета @app.post("/accounts/", response_model=schemas.AccountResponse) def create_account(account: schemas.AccountCreate, db: Session = Depends(get_db)): return crud.create_account(db=db, account=account) @app.get("/accounts/") def read_accounts(db: Session = Depends(get_db)): accounts = crud.get_accounts(db) return accounts # Транзакции @app.post("/transactions/", response_model=schemas.TransactionResponse) def create_transaction(transaction: schemas.TransactionCreate, db: Session = Depends(get_db)): try: # Валидация: income → from_account_id должен быть None или внешний источник if transaction.category == 'income' and transaction.from_account_id is not None: raise HTTPException(status_code=400, detail="Для дохода 'from_account_id' должен быть null") # Проверка баланса для расходов и переводов if transaction.category in ['expense', 'transfer']: account = db.query(models.Account).filter(models.Account.id == transaction.from_account_id).first() if not account: raise HTTPException(status_code=400, detail="Счёт отправителя не найден") if account.balance < transaction.amount: raise HTTPException(status_code=400, detail="Недостаточно средств") # Обновление балансов if transaction.category == 'transfer': # to_account_id обязателен для transfer if transaction.to_account_id is None: raise HTTPException(status_code=400, detail="Для перевода укажите 'to_account_id'") # Проверяем существование получателя to_account = db.query(models.Account).filter(models.Account.id == transaction.to_account_id).first() if not to_account: raise HTTPException(status_code=400, detail="Счёт получателя не найден") # Обновляем оба счёта crud.update_account_balance(db, transaction.from_account_id, -transaction.amount) crud.update_account_balance(db, transaction.to_account_id, transaction.amount) elif transaction.category == 'expense': crud.update_account_balance(db, transaction.from_account_id, -transaction.amount) elif transaction.category == 'income': if transaction.to_account_id is None: raise HTTPException(status_code=400, detail="Для дохода укажите 'to_account_id'") crud.update_account_balance(db, transaction.to_account_id, transaction.amount) # Создание транзакции new_transaction = crud.create_transaction(db=db, transaction=transaction) db.commit() # ✅ Явный commit после всех операций return new_transaction except HTTPException: db.rollback() raise except SQLAlchemyError as e: db.rollback() raise HTTPException(status_code=500, detail=f"Database error: {str(e)}") finally: db.close() @app.get("/transactions/") def read_transactions(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): transactions = crud.get_transactions(db, skip=skip, limit=limit) return transactions @app.get("/") async def health_check(): try: db = SessionLocal() # Версия PostgreSQL version = db.execute(text("SELECT version()")).scalar() # Проверка подключения db.execute(text("SELECT 1")) # Количество банков (с учётом схемы!) bank_count = db.execute( text("SELECT COUNT(*) FROM myschema.banks") ).scalar() db.close() return { "status": "connected", "database": "PostgreSQL", "schema": "myschema", "version": version, "total_banks": bank_count, "timestamp": datetime.utcnow().isoformat(), "message": f"Full system check passed (banks: {bank_count})" } except Exception as e: return {"status": "error", "details": str(e)}