awtkns / fastapi-crudrouter

A dynamic FastAPI router that automatically creates CRUD routes for your models
https://fastapi-crudrouter.awtkns.com
MIT License
1.37k stars 154 forks source link

Example for more than one table. #74

Closed dawnpatrol04 closed 3 years ago

dawnpatrol04 commented 3 years ago

Is there an example for doing more then one table.

Potato - table 1 Meat - table 2

dawnpatrol04 commented 3 years ago

looks like this works :

app.include_router(router) app.include_router(router2)

dawnpatrol04 commented 3 years ago

from sqlalchemy import Column, String, Float, Integer from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker

from pydantic import BaseModel from fastapi import FastAPI from fastapi_crudrouter import SQLAlchemyCRUDRouter

app = FastAPI() engine = create_engine( "postgresql:// " )

SessionLocal = sessionmaker( autocommit=False, autoflush=False, bind=engine )

Base = declarative_base()

def get_db(): session = SessionLocal() try: yield session session.commit() finally: session.close()

######################################################################

class StepCreate(BaseModel): step_name: str step_desc: str function: str created_by: str settings: str

class Step(StepCreate): id: int

class Config:
    orm_mode = True

class StepModel(Base): tablename = 'step' id = Column(Integer, primary_key=True, index=True) step_name = Column(String) step_desc = Column(String) function = Column(String) created_by = Column(String) settings = Column(String)

Base.metadata.create_all(bind=engine)

router = SQLAlchemyCRUDRouter( schema=Step, create_schema=StepCreate, db_model=StepModel, db=get_db, prefix='step' )

#############################################################################

class ServiceCreate(BaseModel): service_name: str service_desc: str function: str created_by: str settings: str

class Service(ServiceCreate): id: int

class Config:
    orm_mode = True

class ServiceModel(Base): tablename = 'service' id = Column(Integer, primary_key=True, index=True) service_name = Column(String) service_desc = Column(String) created_by = Column(String) settings = Column(String)

Base.metadata.create_all(bind=engine)

router2 = SQLAlchemyCRUDRouter( schema=Service, create_schema=ServiceCreate, db_model=ServiceModel, db=get_db, prefix='Service' )

app.include_router(router) app.include_router(router2)

awtkns commented 3 years ago

Glad you figured it out! realized this was not mentioned anywhere in the good. I will add some more clarity regarding it.

dawnpatrol04 commented 3 years ago

Sounds good. Great project. I normally do all of this manually. This is a great for speed to market. Gets a star from me. :)