FastAPI

Tortoise ORM 공식 문서 예제

쿠카이든 2022. 4. 20. 07:56
728x90

Tortoise ORM (Object Relational Mapping)

  • 경로를 생성할 때 Tortoise 모델 TortoiseCRUDRouter을 사용하여 데이터베이스에 자동으로 연결
  • 이를 사용하려면 pydantic 스키마, Tortoise 데이터베이스 모델을 전달하고 FastAPI 앱에 Tortoise ORM을 등록

 

간단한 예제

다음은 필요한 모든 모델을 이미 가져와서 생성했다고 가정한 예입니다.

app = FastAPI()
register_tortoise(app, config=TORTOISE_ORM)

router = TortoiseCRUDRouter(
    schema=MyPydanticModel, 
    db_model=MyDBModel, 
    prefix="test"
)

app.include_router(router)

파일에서 또는 dictionary으로 TORTOISE_ORM을 제공할 수 있습니다. dictionary으로 제공하려면 다음과 같이 하세요.

TORTOISE_ORM = {
    "connections": {"default": 'postgres_url_here'},
    "apps": {
        "models": {
            "models": ["example"],
            "default_connection": "default",
        },
    },
}
  • Where 는 Tortoise 데이터베이스 ORM 모델이 있는 위치를 "models": ["example"]나타냅니다. 
  • 이러한 항목이 많이 있는 경우 파일 example.py로 분할합니다.
  • 데이터베이스 마이그레이션에 Aerich를 사용하는 경우 위에 분할한 내용을 "aerich" 에 추가해야 합니다.
    • 예) aerich의 models.py에 "models": ["models"] 항목 수정

 

  • 데이터베이스에서 생성해야 하므로 기본 ID 필드를 create_schema포함하지 않아야 합니다 . 
  • create_schema를 제공하지 않으면 기본 키가 제거된 스키마가 자동으로 만들어집니다.

Tortoise 전체 예제 코드

# example.py

import uvicorn as uvicorn
from fastapi import FastAPI
from fastapi_crudrouter.core.tortoise import TortoiseCRUDRouter
from tortoise.contrib.fastapi import register_tortoise
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.models import Model
from tortoise import fields, Tortoise

TORTOISE_ORM = {
    "connections": {"default": 'postgres_url'},
    "apps": {
        "models": {
            "models": ["example"],
            "default_connection": "default",
        },
    },
}

# Create Database Tables
async def init():
    await Tortoise.init(config=TORTOISE_ORM)
    await Tortoise.generate_schemas()

app = FastAPI()
register_tortoise(app, config=TORTOISE_ORM)


# Tortoise ORM Model
class TestModel(Model):
    test = fields.IntField(null=False, description=f"Test value")
    ts = fields.IntField(null=False, description=f"Epoch time")


# Pydantic schema
TestSchema = pydantic_model_creator(TestModel, name=f"{TestModel.__name__}Schema")
TestSchemaCreate = pydantic_model_creator(TestModel, name=f"{TestModel.__name__}SchemaCreate", exclude_readonly=True)

# Make your FastAPI Router from your Pydantic schema and Tortoise Model
router = TortoiseCRUDRouter(
    schema=TestSchema,
    create_schema=TestSchemaCreate,
    db_model=TestModel,
    prefix="test"
)

# Add it to your app
app.include_router(router)

if __name__ == "__main__":
    uvicorn.run("example:app", host="127.0.0.1", port=5000, log_level="info")

 

API(CRUD Router) 예제 코드

from pydantic import BaseModel
from fastapi import FastAPI
from fastapi_crudrouter import MemoryCRUDRouter as CRUDRouter

class Potato(BaseModel):
    id: int
    color: str
    mass: float

app = FastAPI()
router = CRUDRouter(schema=Potato)

@router.get('')
def overloaded_get_all():
    return 'My overloaded route that returns all the items'

@router.get('/{item_id}')
def overloaded_get_one():
    return 'My overloaded route that returns one item'

app.include_router(router)
  • 2개의 파일만 작성하여 localhost:8000/docs 에서 API 동작을 확인할 수 있다.

출처 : https://fastapi-crudrouter.awtkns.com/routing

 

Routing - FastAPI CRUD Router

Routing Automatic route generation is the meat and potatoes of CRUDRouter's features. Detail below is how you can prefix, customize, and disable any routes generated by the CRUDRouter. Default Routes By default, the CRUDRouter will generate the six routes

fastapi-crudrouter.awtkns.com

 

728x90

'FastAPI' 카테고리의 다른 글

요즘 핫한 가벼운 파이썬 프레임워크 FastAPI  (0) 2022.04.13