콘텐츠로 이동

FastAPI에서 관계형 데이터베이스로

connection 제너레이터는 FastAPIPython 관계형 데이터베이스 프로젝트에 연결하여, FastAPI 의존성을 통해 타입이 지정된 SQLModel 세션을 라우트 핸들러에 주입합니다.

이 제너레이터를 사용하기 전에 다음이 필요합니다:

  1. py#fast-api 프로젝트
  2. py#rdb 프로젝트
  1. 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
  2. VSCode에서 Nx 콘솔 열기
  3. 클릭 Generate (UI) "Common Nx Commands" 섹션에서
  4. 검색 @aws/nx-plugin - connection
  5. 필수 매개변수 입력
    • 클릭 Generate

    FastAPI 프로젝트를 소스로, 관계형 데이터베이스 프로젝트를 타겟으로 선택하세요.

    매개변수타입기본값설명
    sourceProject 필수string-소스 프로젝트
    targetProject 필수string-연결할 대상 프로젝트
    sourceComponent string-연결을 시작할 소스 컴포넌트 (컴포넌트 이름, 소스 프로젝트 루트 기준 상대 경로, 또는 generator id). 프로젝트를 소스로 명시적으로 선택하려면 '.'을 사용하세요.
    targetComponent string-연결할 대상 컴포넌트 (컴포넌트 이름, 대상 프로젝트 루트 기준 상대 경로, 또는 generator id). 프로젝트를 대상으로 명시적으로 선택하려면 '.'을 사용하세요.
    preferInstallDependencies booleantrue생성기 실행 후 의존성 설치를 선호할지 여부입니다. 여러 생성기를 일괄 처리할 때 설치를 연기하려면 false로 설정하세요 (후속 생성기가 Nx 프로젝트 그래프를 계산할 수 있도록 필요한 경우 설치는 여전히 실행됩니다); 마지막에 한 번만 설치합니다.

    제너레이터는 FastAPI 프로젝트를 수정합니다:

    • 디렉터리packages/my_api
      • project.json dev가 데이터베이스의 dev 타겟에 의존성 추가
      • pyproject.toml 데이터베이스 패키지를 워크스페이스 종속성으로 추가
      • 디렉터리my_api
        • 디렉터리dependencies
          • my_db.py 데이터베이스 세션을 위한 FastAPI MyDbSession 의존성

    라우트 핸들러에서 데이터베이스 사용

    섹션 제목: “라우트 핸들러에서 데이터베이스 사용”

    이 제너레이터는 라우트 핸들러에서 사용할 수 있는 주입 가능한 FastAPI Dependency를 구성합니다:

    packages/my_api/my_api/api.py
    from sqlmodel import select
    from my_api.dependencies.my_db import MyDbSession
    from my_scope.my_db.models.example import ExampleModel
    @app.get("/examples")
    async def list_examples(my_db: MyDbSession):
    return (await my_db.execute(select(ExampleModel))).all()
    @app.post("/examples")
    async def create_example(name: str, my_db: MyDbSession):
    item = ExampleModel(name=name)
    my_db.add(item)
    await my_db.commit()
    await my_db.refresh(item)
    return item

    FastAPI는 요청당 새 세션을 자동으로 열고 핸들러가 반환될 때 닫습니다.

    런타임에 FastAPI Lambda 함수가 데이터베이스에 연결할 수 있도록 하려면, 데이터베이스와 동일한 VPC에 배포되어야 하며 네트워크 및 IAM 액세스 권한이 부여되어야 합니다.

    애플리케이션 스택에서 API를 데이터베이스와 동일한 VPC에 배포한 다음, allowDefaultPortFromgrantConnect를 호출하여 네트워크 경로를 열고 Lambda 핸들러에 IAM rds-db:connect 권한을 부여하세요:

    packages/infra/src/stacks/application-stack.ts
    import { MyDatabase } from ':my-scope/common-constructs';
    const db = new MyDatabase(this, 'Db', { vpc, ... });
    const api = new MyApi(this, 'Api', {
    integrations: MyApi.defaultIntegrations(this)
    .withDefaultOptions({
    vpc,
    vpcSubnets: { subnetType: SubnetType.PRIVATE_WITH_EGRESS },
    })
    .build(),
    });
    Object.entries(api.integrations).forEach(([operation, integration]) => {
    db.allowDefaultPortFrom(integration.handler, `Allow ${operation} to connect to the database`);
    db.grantConnect(integration.handler);
    });

    API Lambda 함수를 프라이빗 격리 서브넷이 아닌 이그레스가 있는 프라이빗 서브넷에 배포하세요. 런타임에 session_context()는 AWS AppConfig에서 데이터베이스 구성을 검색하는데, 이는 아웃바운드 인터넷 액세스가 필요한 퍼블릭 AWS 서비스 엔드포인트입니다.

    Terminal window
    pnpm nx dev <project-name>

    이렇게 하면 FastAPI와 연결된 모든 데이터베이스가 시작됩니다. LOCAL_DEV=true 환경 변수는 데이터베이스 클라이언트가 Aurora 대신 로컬 Docker 데이터베이스에 연결하도록 합니다.