async def connect_to_es(): settings = config.get_settings() hosts = settings.es_hosts opts = {} if (settings.es_user is not None and settings.es_password is not None): opts["http_auth"] = (settings.es_user, settings.es_password) db.client = AsyncElasticsearch(hosts, **opts)
def health_check(): settings: Settings = get_settings() return { "title": settings.WEB_APP_TITLE, "description": settings.WEB_APP_DESCRIPTION, "version": settings.WEB_APP_VERSION, "status": StatusEnum.OK, "expire_time": settings.ACCESS_TOKEN_EXPIRE_MINUTES, }
from typing import List, Optional from app.core.config import Settings, get_settings from app.infra.httpx.client import HTTPXClient from app.schemas.owner import Owner from app.schemas.search import VehicleQueryParams from app.schemas.vehicle import CreateVehicle, UpdateVehicle, Vehicle, VehicleInDB from app.schemas.vehicle_x_owner import VehicleXOwner httpx_client = HTTPXClient() settings: Settings = get_settings() class VehicleService: def __init__(self): return async def get_by_plate(self, *, vehicle_id: str) -> Vehicle: url = f"{settings.DATABASE_URL}/api/vehicles/{vehicle_id}" header = {"Content-Type": "application/json"} response = await httpx_client.get(url_service=url, status_response=200, headers=header, timeout=40) return response async def create(self, *, vehicle_in: CreateVehicle) -> CreateVehicle: url = f"{settings.DATABASE_URL}/api/vehicles" header = {"Content-Type": "application/json"} vehicle = vehicle_in.dict()
import jwt from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from pydantic import ValidationError from tortoise.exceptions import DoesNotExist from app import schemas from app.core import security from app.core.config import get_settings from app.models.user import UserPydantic, User settings = get_settings() auth_scheme = HTTPBearer() async def get_current_user( token: HTTPAuthorizationCredentials = Depends(auth_scheme), ) -> UserPydantic: try: payload = jwt.decode(token.credentials, settings.SECRET_KEY, algorithms=[security.ALGORITHM]) token_data = schemas.TokenPayload(**payload) except (jwt.PyJWTError, ValidationError): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials", ) try: return await User.get(id=token_data.sub)
from fastapi import FastAPI from app.api.api_v1.api import api_router from app.core import es from app.core.config import get_settings def create_app() -> FastAPI: app = FastAPI() app.add_event_handler("startup", es.connect) app.add_event_handler("shutdown", es.close) app.include_router(api_router, prefix="/api/v1") return app app = create_app() if __name__ == "__main__": uvicorn.run("main:app", port=get_settings().port)
import pytest import yaml from app.db import Base from app.db import User, Dog from app.db import get_db from fastapi.testclient import TestClient from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from app.core import config from app.main import app settings = config.get_settings() SQLALCHEMY_DATABASE_URL = f"postgresql://{settings.user_db}:{settings.password_db}@{settings.host}:{settings.port_db}/{settings.database_testing}" _engine = create_engine(SQLALCHEMY_DATABASE_URL) Base.metadata.create_all(bind=_engine) Session = sessionmaker(bind=_engine) s = Session() SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=_engine) @pytest.fixture(scope="function") def test_app(): app.dependency_overrides[get_db] = override_get_db with TestClient(app) as test_client: yield test_client @pytest.fixture(autouse=True, scope="function") def recreateDB():