Skip to content

swarmauri/crouton

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Swamauri Logo
Hits License
PyPI - Crouton Version PyPI - Crouton Downloads PyPI - Crouton-Client Version PyPI - Crouton-Client Downloads
Python


Crouton

crouton streamlines CRUD operations in FastAPI applications by auto-generating endpoints for SQLAlchemy models, reducing the need for repetitive code and improving development speed.

By integrating Pydantic for data validation, Crouton ensures type safety and consistent data handling, allowing developers to focus on application logic instead of boilerplate code.

Installation

Prerequisites

To install Crouton libraries. Run the following command:

pip install crouton
pip install crouton-client

Development Release Installation

pip install crouton --pre
pip install crouton-client --pre

Basic Usage

Below is a simple example of what the CRUDRouter can do. In just ten lines of code, you can generate all the crud routes you need for any model. A full list of the routes generated can be found here.

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 crouton import SQLAlchemyCRUDRouter

app = FastAPI()
engine = create_engine(
    "sqlite:///./app.db",
    connect_args={"check_same_thread": False}
)

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 PotatoCreate(BaseModel):
    thickness: float
    mass: float
    color: str
    type: str


class Potato(PotatoCreate):
    id: int

    class Config:
        orm_mode = True


class PotatoModel(Base):
    __tablename__ = 'potatoes'
    id = Column(Integer, primary_key=True, index=True)
    thickness = Column(Float)
    mass = Column(Float)
    color = Column(String)
    type = Column(String)


Base.metadata.create_all(bind=engine)

router = SQLAlchemyCRUDRouter(
    schema=Potato,
    create_schema=PotatoCreate,
    db_model=PotatoModel,
    db=get_db,
    prefix='potato'
)

app.include_router(router)

Example

image


Using the CroutonClient

CroutonClient is a Python library for streamlined REST API interactions, supporting both synchronous and asynchronous operations for CRUD tasks.


Initialization

from crouton_client import CroutonClient

client = CroutonClient(API_ROOT="https://api.example.com", ACCESS_STRING="your-token")

Common Operations

GET

  • Synchronous:
    response = client.get(resource="items", item_id="123", filters={"status": "active"})
  • Asynchronous:
    response = await client.aget(resource="items", item_id="123")

POST

  • Synchronous:
    response = client.post(resource="items", data_obj={"name": "Item", "price": 10.0})
  • Asynchronous:
    response = await client.apost(resource="items", data_obj={"name": "Item", "price": 10.0})

PUT

  • Synchronous:
    response = client.put(resource="items", data_obj={"price": 15.0}, item_id="123")
  • Asynchronous:
    response = await client.aput(resource="items", data_obj={"price": 15.0}, item_id="123")

DELETE

  • Synchronous:
    response = client.delete(resource="items", item_id="123")
  • Asynchronous:
    response = await client.adelete(resource="items", item_id="123")

Features

  1. Synchronous & Asynchronous: Methods available for GET, POST, PUT, DELETE.
  2. Authentication: Pass ACCESS_STRING for token-based requests.
  3. Auto-Generated IDs: post and apost auto-generate id fields if not provided.
  4. Logging: Logs all requests and responses for debugging.

Error Handling

Raises ValueError for failed requests:

try:
    client.get(resource="invalid")
except ValueError as e:
    print(f"Error: {e}")

Summary Table

Operation Synchronous Asynchronous
GET get() aget()
POST post() apost()
PUT put() aput()
DELETE delete() adelete()

CroutonClient simplifies REST API interactions, allowing you to focus on application logic instead of repetitive request handling.