### Minimum working example after migration Source: https://rasinmuhammed.github.io/opsdeck/recipes/migration-from-fastapi-admin A complete setup showing the initialization of FastAPI, SQLAlchemy models for users and audit logs, and the configuration of the OpsDeck admin interface. ```python from fastapi import FastAPI from sqlalchemy import String, Boolean from sqlalchemy.ext.asyncio import create_async_engine from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from opsdeck import OpsDeck from opsdeck.auth.models import AdminUserMixin from opsdeck.audit.models import AuditLog app = FastAPI() engine = create_async_engine("sqlite+aiosqlite:///./app.db") class Base(DeclarativeBase): pass class AdminUser(AdminUserMixin, Base): __tablename__ = "admin_users" id: Mapped[int] = mapped_column(primary_key=True) username: Mapped[str] = mapped_column(String(100), unique=True) is_active: Mapped[bool] = mapped_column(Boolean, default=True) is_superuser: Mapped[bool] = mapped_column(Boolean, default=False) class AdminAuditLog(AuditLog, Base): __tablename__ = "admin_audit_log" id: Mapped[int] = mapped_column(primary_key=True) class User(Base): __tablename__ = "users" id: Mapped[int] = mapped_column(primary_key=True) username: Mapped[str] = mapped_column(String(50), unique=True) email: Mapped[str] = mapped_column(String(200), unique=True) is_active: Mapped[bool] = mapped_column(Boolean, default=True) def __admin_repr__(self) -> str: return self.username admin = OpsDeck( app, engine=engine, secret_key="change-me-in-production", title="My Admin", auth_model=AdminUser, audit_model=AdminAuditLog, ) admin.auto_discover(Base) @app.on_event("startup") async def startup(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) ``` -------------------------------- ### Install and initialize Alembic Source: https://rasinmuhammed.github.io/opsdeck/recipes/migration-from-fastapi-admin Commands to install Alembic and initialize the migration environment. ```bash pip install alembic alembic init alembic ``` -------------------------------- ### Install OpsDeck with pip Source: https://rasinmuhammed.github.io/opsdeck/guide/getting-started Install the opsdeck package using pip. ```bash pip install opsdeck ``` -------------------------------- ### Basic OpsDeck setup with FastAPI and SQLAlchemy Source: https://rasinmuhammed.github.io/opsdeck/guide/getting-started Create a FastAPI app, an async SQLAlchemy engine, and an OpsDeck instance. The secret_key should be changed in production. ```python from fastapi import FastAPI from sqlalchemy.ext.asyncio import create_async_engine from opsdeck import OpsDeck app = FastAPI() engine = create_async_engine("sqlite+aiosqlite:///./app.db") admin = OpsDeck( app, engine=engine, secret_key="change-me-in-production", title="Operations", ) ``` -------------------------------- ### Initialize OpsDeck with explicit configuration Source: https://rasinmuhammed.github.io/opsdeck/recipes/ai-friendly-integration This example demonstrates the recommended pattern for initializing the OpsDeck instance with explicit auth, audit, and view registration to ensure clarity for AI assistants. ```python from opsdeck import OpsDeck from .admin_views import UserAdmin, TicketAdmin admin = OpsDeck( app, engine=engine, secret_key=settings.ADMIN_SECRET_KEY, auth_model=AdminUser, audit_model=AdminAuditLog, ) admin.add_view(UserAdmin) admin.add_view(TicketAdmin) ``` -------------------------------- ### OpsDeck signed cookie setup Source: https://rasinmuhammed.github.io/opsdeck/recipes/migration-from-fastapi-admin Shows OpsDeck initialization using signed session cookies instead of Redis. The secret_key signs the cookies and auth_model is optional. ```python # OpsDeck — no Redis needed from opsdeck import OpsDeck admin = OpsDeck( app, engine=engine, secret_key="your-32-char-secret-key", # Signs session cookies auth_model=AdminUser, ) ``` -------------------------------- ### fastapi-admin Redis session setup Source: https://rasinmuhammed.github.io/opsdeck/recipes/migration-from-fastapi-admin Shows the Redis-based session storage setup required by fastapi-admin. It creates a Redis pool and passes it to app.init along with the admin path. ```python # fastapi-admin — Redis required import aioredis from fastapi_admin.providers.login import UsernamePasswordProvider redis = await aioredis.create_redis_pool("redis://localhost") await app.init( redis=redis, admin_path="/admin", ... ) ``` -------------------------------- ### Run the app with uvicorn Source: https://rasinmuhammed.github.io/opsdeck/guide/getting-started Start the FastAPI application with uvicorn in reload mode. The admin interface is available at http://localhost:8000/admin. ```bash uvicorn main:app --reload ``` -------------------------------- ### Authentication setup with auth_model and audit_model Source: https://rasinmuhammed.github.io/opsdeck/guide/getting-started Pass auth_model and audit_model to OpsDeck to require authentication and enable audit logging. Set ADMIN_SECURE_COOKIES=true in production for secure cookies. ```python admin = OpsDeck( app, engine=engine, secret_key="change-me", auth_model=AdminUser, audit_model=AdminAuditLog, ) ``` -------------------------------- ### register() options Source: https://rasinmuhammed.github.io/opsdeck/guide/configuration Registers a model with OpsDeck. The example enables searchable fields, filters, and permission-based view/edit access. The eager_load option preloads related objects to avoid N+1 queries. ```python admin.register( User, list_display=["id", "email"], searchable_fields=["email"], filter_fields=["is_active"], permissions={"view": ["*"], "edit": ["admin"]}, eager_load=["organization"], ) ``` -------------------------------- ### SQLAlchemy 2.x model (OpsDeck) Source: https://rasinmuhammed.github.io/opsdeck/recipes/migration-from-fastapi-admin Example of a User model defined with SQLAlchemy 2.x declarative models, as used in OpsDeck. This model uses Mapped and mapped_column with type annotations, and specifies the table name via __tablename__. ```python # OpsDeck (SQLAlchemy 2.x) from sqlalchemy import String, Boolean, DateTime from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from datetime import datetime class Base(DeclarativeBase): pass class User(Base): __tablename__ = "users" id: Mapped[int] = mapped_column(primary_key=True) username: Mapped[str] = mapped_column(String(50), unique=True) email: Mapped[str] = mapped_column(String(200), unique=True) is_active: Mapped[bool] = mapped_column(Boolean, default=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow) ``` -------------------------------- ### Tortoise ORM model (fastapi-admin) Source: https://rasinmuhammed.github.io/opsdeck/recipes/migration-from-fastapi-admin Example of a User model defined with Tortoise ORM, as used in fastapi-admin. This model uses fields like CharField, BooleanField, and DatetimeField, and specifies the table name in the Meta class. ```python # fastapi-admin (Tortoise ORM) from tortoise import fields, models class User(models.Model): username = fields.CharField(max_length=50, unique=True) email = fields.CharField(max_length=200, unique=True) is_active = fields.BooleanField(default=True) created_at = fields.DatetimeField(auto_now_add=True) class Meta: table = "users" ``` -------------------------------- ### fastapi-admin startup initialization Source: https://rasinmuhammed.github.io/opsdeck/recipes/migration-from-fastapi-admin Shows the full fastapi-admin initialization inside a startup event, including Tortoise ORM init and the admin app init with a username/password provider. ```python # fastapi-admin from fastapi_admin.app import app as admin_app from fastapi_admin.providers.login import UsernamePasswordProvider @app.on_event("startup") async def startup(): await Tortoise.init(config=TORTOISE_ORM) await admin_app.init( admin_path="/admin", engine=TortoiseEngine(), providers=[ UsernamePasswordProvider( admin_model=Admin, login_logo_url="...", ) ], redis=redis, ) ``` -------------------------------- ### OpsDeck initialization and model registration Source: https://rasinmuhammed.github.io/opsdeck/recipes/migration-from-fastapi-admin Shows OpsDeck initialization with an async SQLAlchemy engine, optional auth and audit models, and explicit model registration or auto-discovery. ```python # OpsDeck from fastapi import FastAPI from sqlalchemy.ext.asyncio import create_async_engine from opsdeck import OpsDeck app = FastAPI() engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db") admin = OpsDeck( app, engine=engine, secret_key="your-32-char-secret-key", title="My Admin", auth_model=AdminUser, # optional — removes auth if omitted audit_model=AuditLog, # optional — enables audit logging ) # Register models explicitly admin.register(User) admin.register(Product) # Or auto-discover all models admin.auto_discover(Base) ``` -------------------------------- ### Initialize OpsDeck with Auth and Audit Source: https://rasinmuhammed.github.io/opsdeck/recipes/auth-and-audit Configures the OpsDeck instance with authentication and audit models to enable secure admin flows and durable change history. ```python from opsdeck import OpsDeck admin = OpsDeck( app, engine=engine, secret_key=settings.ADMIN_SECRET_KEY, auth_model=AdminUser, audit_model=AdminAuditLog, title="Operations", ) ``` -------------------------------- ### OpsDeck constructor Source: https://rasinmuhammed.github.io/opsdeck/guide/configuration Initializes the OpsDeck admin instance. The engine option enables database-backed CRUD, search, export, and relationship lookups. Setting auth_model and audit_model enables admin login, permission checks, and audit history. secure_cookies forces secure session cookies regardless of environment defaults. ```python admin = OpsDeck( app, secret_key="change-me", engine=engine, title="Operations", prefix="/admin", auth_model=AdminUser, audit_model=AdminAuditLog, secure_cookies=True, ) ``` -------------------------------- ### OpsDeck Constructor Source: https://rasinmuhammed.github.io/opsdeck/api The main entrypoint for integrating the admin into a FastAPI application. ```python OpsDeck( app, secret_key, *, engine=None, title="Admin", prefix="/admin", templates_dir=None, add_csp_middleware=True, max_recursion_depth=5, auth_model=None, audit_model=None, demo_mode=False, secure_cookies=None, ) ``` -------------------------------- ### OpsDeck Constructor Source: https://rasinmuhammed.github.io/opsdeck/api Initializes the OpsDeck admin integration with a FastAPI app. Configure the database engine, authentication, audit logging, and other options. ```APIDOC ## OpsDeck Constructor ### Description Initializes the OpsDeck admin integration with a FastAPI app. ### Method Constructor ### Signature OpsDeck(app, secret_key, *, engine=None, title="Admin", prefix="/admin", templates_dir=None, add_csp_middleware=True, max_recursion_depth=5, auth_model=None, audit_model=None, demo_mode=False, secure_cookies=None) ### Parameters - **app** (FastAPI) - Required - The FastAPI application instance. - **secret_key** (str) - Required - Secret key for signing and security. - **engine** (async SQLAlchemy Engine) - Optional - Async SQLAlchemy engine for database-backed admin features. - **title** (str) - Optional - Title of the admin interface. Defaults to "Admin". - **prefix** (str) - Optional - URL prefix for the admin routes. Defaults to "/admin". - **templates_dir** (str) - Optional - Directory for custom templates. - **add_csp_middleware** (bool) - Optional - Whether to add Content Security Policy middleware. Defaults to True. - **max_recursion_depth** (int) - Optional - Maximum recursion depth for certain operations. Defaults to 5. - **auth_model** (Model) - Optional - Admin user model used for login and permission checks. - **audit_model** (Model) - Optional - Concrete audit log model to persist change history. - **demo_mode** (bool) - Optional - Enable demo mode. Defaults to False. - **secure_cookies** (bool) - Optional - Override secure-cookie behavior directly; otherwise use the ADMIN_SECURE_COOKIES environment variable. ``` -------------------------------- ### Prompt to add a first admin Source: https://rasinmuhammed.github.io/opsdeck/ai-assistants Prompt for adding a first admin with OpsDeck. It instructs to use the existing async SQLAlchemy engine, auto-discover models from Base, mount at /admin, and keep the integration minimal and production-safe. ```text Add OpsDeck to this project using the existing async SQLAlchemy engine. Auto-discover models from Base. Mount it at /admin. Keep the integration minimal and production-safe. ``` -------------------------------- ### Generate and apply Alembic migrations Source: https://rasinmuhammed.github.io/opsdeck/recipes/migration-from-fastapi-admin Commands to generate an initial migration script and apply it to the database. ```bash alembic revision --autogenerate -m "initial" alembic upgrade head ``` -------------------------------- ### ModelAdmin class Source: https://rasinmuhammed.github.io/opsdeck/guide/configuration Defines a reusable declarative admin configuration instead of a long register() call. Instructor sets the model and attribute configurations like display filter permissions. ```python class InvoiceAdmin(ModelAdmin): model = Invoice menu_label = "Invoices" list_display = ["id", "customer_id", "status", "created_at"] filter_fields = ["status", "created_at"] permissions = {"view": ["*"], "export": ["finance", "admin"]} ``` -------------------------------- ### OpsDeck.auto_discover Source: https://rasinmuhammed.github.io/opsdeck/api Registers all supported declarative models automatically. ```APIDOC ## OpsDeck.auto_discover ### Description Registers all supported declarative models automatically. ### Method auto_discover(Base, include=None, exclude=None) ### Parameters - **Base** (DeclarativeBase) - Required - The SQLAlchemy declarative base class. - **include** (list) - Optional - List of model names to include. If None, all are included. - **exclude** (list) - Optional - List of model names to exclude. ``` -------------------------------- ### OpsDeck.register Source: https://rasinmuhammed.github.io/opsdeck/api Quick registration path for a model with the admin interface. ```APIDOC ## OpsDeck.register ### Description Quick registration path for a model with the admin interface. ### Method register(model, **options) ### Parameters - **model** (Model) - Required - The SQLAlchemy model to register. - **options** (dict) - Optional - Additional configuration options for the model. ``` -------------------------------- ### OpsDeck.add_view Source: https://rasinmuhammed.github.io/opsdeck/api Advanced registration path using a ModelAdmin subclass. ```APIDOC ## OpsDeck.add_view ### Description Advanced registration path using a ModelAdmin subclass for reusable admin behavior. ### Method add_view(ModelAdminSubclass) ### Parameters - **ModelAdminSubclass** (ModelAdmin) - Required - A subclass of ModelAdmin that defines the admin configuration. ``` -------------------------------- ### Good prompt for adding OpsDeck to a FastAPI app Source: https://rasinmuhammed.github.io/opsdeck/ai-assistants A recommended prompt for AI coding assistants when integrating OpsDeck into a FastAPI application. It specifies the framework, ORM path, models, permissions, scoping, filters, and explicitly instructs not to add Node.js or frontend build tooling. ```text Add OpsDeck to this FastAPI app. Use the existing async SQLAlchemy engine and models. Register User, Organization, and Invoice. Require admin login with my AdminUser model. Scope Invoice visibility by organization for non-superusers. Add filters for status and created_at. Do not introduce Node.js or frontend build tooling. ``` -------------------------------- ### Prompt to add a serious admin Source: https://rasinmuhammed.github.io/opsdeck/ai-assistants Prompt for adding a serious admin with OpsDeck. It instructs to use ModelAdmin classes, AdminUser for authentication, AdminAuditLog for audit history, full CRUD for Users and Organizations, scoping by organization, and adding list columns, search fields, filter fields, and CSV export. ```text Integrate OpsDeck using ModelAdmin classes instead of only register(). Use AdminUser for authentication and AdminAuditLog for audit history. Give Users and Organizations full CRUD to admins. Scope invoices and tickets by the current user's organization. Add list columns, search fields, filter fields, and CSV export. ``` -------------------------------- ### Register Product with filter_fields Source: https://rasinmuhammed.github.io/opsdeck/features Register a model with OpsDeck's admin and specify which fields appear in the sidebar filters. The filter_fields list includes 'available', 'created_at', and 'price'. ```python admin.register( Product, filter_fields=["available", "created_at", "price"], ) ``` -------------------------------- ### Prompt to add a tenant-safe admin Source: https://rasinmuhammed.github.io/opsdeck/ai-assistants Prompt for adding a tenant-safe admin with OpsDeck. It instructs to use row_scope for organization-based visibility, protect admin routes with the existing AdminUser auth model, and add bulk actions only where permissions allow. ```text Add OpsDeck to this multi-tenant FastAPI app. Use row_scope so non-superusers only see records from their organization. Protect all admin routes with the existing AdminUser auth model. Add bulk actions only where permissions allow them. ``` -------------------------------- ### Configure Alembic target metadata Source: https://rasinmuhammed.github.io/opsdeck/recipes/migration-from-fastapi-admin Setting the target metadata in alembic/env.py to point to the SQLAlchemy Base model. ```python from your_app.models import Base target_metadata = Base.metadata ``` -------------------------------- ### Auto-discover models with admin.auto_discover Source: https://rasinmuhammed.github.io/opsdeck/guide/getting-started Register all models automatically by calling auto_discover on the Base metadata. ```python admin.auto_discover(Base) ``` -------------------------------- ### Explicit model registration with admin.register Source: https://rasinmuhammed.github.io/opsdeck/guide/getting-started Register a single model with custom list, search, and filter fields. ```python admin.register( User, list_display=["id", "email", "is_active"], searchable_fields=["email"], filter_fields=["is_active", "created_at"], ) ``` -------------------------------- ### Define a custom bulk action with AdminAction Source: https://rasinmuhammed.github.io/opsdeck/recipes/actions-and-ops Defines an async handler that updates multiple invoice records to 'approved' status and registers it as an AdminAction on a ModelAdmin. Use this pattern for bulk operations like approvals or status transitions. The handler receives request, session, model, ids, user, and config, and returns a result with the count of approved items. ```python from opsdeck import AdminAction, ModelAdmin async def approve_invoices(*, request, session, model, ids, user, config): await session.execute( model.__table__.update() .where(model.id.in_(ids)) .values(status="approved") ) return {"ok": True, "approved": len(ids)} class InvoiceAdmin(ModelAdmin): model = Invoice actions = [ AdminAction( name="approve_invoices", label="Approve invoices", handler=approve_invoices, ) ] ``` -------------------------------- ### ModelAdmin Configuration Source: https://rasinmuhammed.github.io/opsdeck/api Declarative advanced configuration for a model, used for reusable admin behavior or complex registration options. ```python class UserAdmin(ModelAdmin): model = User list_display = ["id", "email", "is_active"] permissions = {"view": ["*"], "edit": ["admin"]} ``` -------------------------------- ### Define AdminUser model in OpsDeck Source: https://rasinmuhammed.github.io/opsdeck/recipes/migration-from-fastapi-admin The equivalent model structure using OpsDeck's AdminUserMixin with SQLAlchemy. ```python # OpsDeck from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from sqlalchemy import String from opsdeck.auth.models import AdminUserMixin class Base(DeclarativeBase): pass class AdminUser(AdminUserMixin, Base): __tablename__ = "admin_users" id: Mapped[int] = mapped_column(primary_key=True) username: Mapped[str] = mapped_column(String(100), unique=True) # password_hash is provided by AdminUserMixin is_active: Mapped[bool] = mapped_column(default=True) is_superuser: Mapped[bool] = mapped_column(default=False) ``` -------------------------------- ### AdminAction Source: https://rasinmuhammed.github.io/opsdeck/api Defines a custom admin action. ```APIDOC ## AdminAction ### Description Defines a custom admin action. ### Fields - **name** - The name of the action. - **label** - The display label for the action. - **handler** - The function that handles the action. - **confirmation_message** - Optional message to show for confirmation. - **bulk** - Whether the action applies to multiple items. - **visible** - Whether the action is visible. ``` -------------------------------- ### ModelAdmin Source: https://rasinmuhammed.github.io/opsdeck/api Declarative advanced configuration for a model. Useful for reusable admin behavior or complex configurations. ```APIDOC ## ModelAdmin ### Description Declarative advanced configuration for a model. Useful when you need reusable admin behavior or more than a handful of register() options. ### Example class UserAdmin(ModelAdmin): model = User list_display = ["id", "email", "is_active"] permissions = {"view": ["*"], "edit": ["admin"]} ### Fields - **model** - The SQLAlchemy model to configure. - **list_display** - List of field names to display in the list view. - **permissions** - Dictionary defining view and edit permissions. ``` -------------------------------- ### Define Admin model in fastapi-admin Source: https://rasinmuhammed.github.io/opsdeck/recipes/migration-from-fastapi-admin The original model structure using fastapi-admin's AbstractAdmin mixin with Tortoise ORM. ```python # fastapi-admin from fastapi_admin.models import AbstractAdmin class Admin(AbstractAdmin): last_login = fields.DatetimeField(description="Last Login", default=datetime.datetime.now) email = fields.CharField(max_length=200, default="") ... class Meta: table = "admin" ``` -------------------------------- ### DetailPanel Source: https://rasinmuhammed.github.io/opsdeck/api Adds custom detail content to edit/detail pages. ```APIDOC ## DetailPanel ### Description Adds custom detail content to edit/detail pages. ``` -------------------------------- ### Define __admin_repr__ for searchable dropdowns Source: https://rasinmuhammed.github.io/opsdeck/features Add __admin_repr__ to a SQLAlchemy model to control the label shown in OpsDeck's searchable dropdowns for ForeignKey columns. The method returns the string used in the dropdown, here the author's name. ```python class Author(Base): __tablename__ = "authors" name = Column(String) def __admin_repr__(self): return self.name # Use this in dropdowns ``` -------------------------------- ### DashboardCard Source: https://rasinmuhammed.github.io/opsdeck/api Adds custom dashboard content from application-aware renderers. ```APIDOC ## DashboardCard ### Description Adds custom dashboard content from application-aware renderers. ``` -------------------------------- ### OpsDeck.get_session_dependency Source: https://rasinmuhammed.github.io/opsdeck/api Exposes the admin session dependency for use in custom routes. ```APIDOC ## OpsDeck.get_session_dependency ### Description Exposes the admin session dependency for use in custom routes. ### Method get_session_dependency() ### Returns - The admin session dependency. ``` -------------------------------- ### Advanced ModelAdmin class with permissions and row_scope Source: https://rasinmuhammed.github.io/opsdeck/guide/getting-started Define a custom ModelAdmin subclass to control menu label, display fields, permissions, and row-level scoping. The row_scope method restricts queries for non-superusers. ```python from opsdeck import ModelAdmin class UserAdmin(ModelAdmin): model = User menu_label = "Users" list_display = ["id", "email", "is_active", "created_at"] searchable_fields = ["email"] filter_fields = ["is_active", "created_at"] permissions = { "view": ["*"], "create": ["admin"], "edit": ["admin"], "delete": ["admin"], "export": ["admin"], } @staticmethod def row_scope(*, request, query, session, user): if user and not user.is_superuser: return query.where(User.organization_id == user.organization_id) return query admin.add_view(UserAdmin) ``` -------------------------------- ### Implement row_scope in ModelAdmin Source: https://rasinmuhammed.github.io/opsdeck/recipes/multi-tenant-scoping Define the row_scope static method within a ModelAdmin class to filter queries based on the user's organization_id, unless the user is a superuser. ```python from opsdeck import ModelAdmin class InvoiceAdmin(ModelAdmin): model = Invoice list_display = ["id", "customer_id", "status", "created_at"] searchable_fields = ["id"] filter_fields = ["status", "created_at"] @staticmethod def row_scope(*, request, query, session, user): if user is None or user.is_superuser: return query return query.where(Invoice.organization_id == user.organization_id) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.