semvec/pypi-packages huggingface dataset:
sqlmodelclassapi 0.1.0
Add your description here
Requires Python: >=3.12

# SQLModel support for classApi

This project provides a simple way to use a SQLModel `Session` inside your classApi views.

First, create your SQLModel engine. Here is a basic example:

```py
# engine.py
from sqlalchemy import create_engine
from sqlmodel import SQLModel

from .model import User  # In this example, User has 3 fields: id, name, and email


sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"

engine = create_engine(sqlite_url, echo=True)

def create_db_and_tables():
    SQLModel.metadata.create_all(engine)
```

Then create a new base view using `make_session_view`:

```py
# engine.py
from sqlalchemy import create_engine
from sqlmodel import SQLModel

from sqlmodelclassapi.main import make_session_view
from .model import User


sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"

engine = create_engine(sqlite_url, echo=True)

def create_db_and_tables():
    SQLModel.metadata.create_all(engine)

SessionView = make_session_view(engine=engine)  # New base view with session support
```

Now, to create a view, inherit from `SessionView` instead of `BaseView`:

```py
# views.py
class ExampleSessionView(SessionView):
    methods = ["GET", "POST"]

    def get(self, *args):
        statement = select(User)
        results = self.session.exec(statement).all()
        return [
            {"id": user.id, "name": user.name, "email": user.email}
            for user in results
        ]

    def post(self, name: str):
        new_user = User(name=name, email=f"{name.lower()}@example.com")
        self.session.add(new_user)
        self.session.commit()
        self.session.refresh(new_user)

        return {"message": f"User '{name}' created successfully!", "user": new_user}
```

With this setup, all operations in your request run inside the same session, including `pre_{method}` hooks.