fastapi with sqlalchemy code example

Example 1: insert into relational database fastapi

def create_nested_family(db: Session, family: schemas.NestedFamilyCreate):
    # split information in family and members
    family_data = family.dict()
    member_data = family_data.pop('members', None)   # ToDo: handle error if no members
    db_family = models.Family(**family_data)
    db.add(db_family)
    db.commit()
    db.refresh(db_family)
    # get family_id
    family_id = db_family.id
    # add members
    for m in member_data:
        m['family_id'] = family_id
        db_member = models.Member(**m)
        db.add(db_member)
        db.commit()
        db.refresh(db_member)
    return db_family

Example 2: fast api postgres

from logging.config import fileConfigfrom sqlalchemy import engine_from_configfrom sqlalchemy import poolfrom alembic import context# this is the Alembic Config object, which provides# access to the values within the .ini file in use.config = context.config# Interpret the config file for Python logging.# This line sets up loggers basically.fileConfig(config.config_file_name)# add your model's MetaData object here# for 'autogenerate' support# from myapp import mymodel# target_metadata = mymodel.Base.metadatatarget_metadata = None