CRUDAdmin Class API Reference¶
Class Definition¶
A FastAPI admin interface for your SQLAlchemy models.
It mounts as a sub-application, keeps its admins, sessions and event log in an admin database of its own, and protects every page with a login.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Callable[[], AsyncGenerator[AsyncSession, None]]
|
Your app's async session dependency; the admin reads and writes your models through it. |
required |
SECRET_KEY
|
str
|
Keys the stored session ids and CSRF tokens. Use at least 32
random bytes, kept out of version control, for example from
|
required |
mount_path
|
str | None
|
Where the admin is mounted, |
'/admin'
|
theme
|
str | None
|
|
'dark-theme'
|
admin_db_url
|
str | None
|
The admin database's URL. Defaults to SQLite in
|
None
|
admin_db_path
|
str | None
|
A path for a SQLite admin database, instead of a URL. |
None
|
db_config
|
DatabaseConfig | None
|
A |
None
|
setup_on_initialization
|
bool
|
Mount the routes now; with False, call
|
True
|
initial_admin
|
dict | BaseModel | None
|
Credentials of a superuser created by |
None
|
track_events
|
bool
|
Record logins, logouts and every create, update and delete in the event log. |
False
|
sessions
|
SessionConfig | None
|
How sessions are kept: a SessionConfig. |
None
|
access
|
AccessConfig | None
|
Who may reach the admin: an AccessConfig. |
None
|
allowed_ips
|
list[str] | None
|
Deprecated; use |
None
|
allowed_networks
|
list[str] | None
|
Deprecated; use |
None
|
max_sessions_per_user
|
int | None
|
Deprecated; use |
None
|
session_timeout_minutes
|
int | None
|
Deprecated; use |
None
|
cleanup_interval_minutes
|
int | None
|
Deprecated; use
|
None
|
secure_cookies
|
bool | None
|
Deprecated; use |
None
|
enforce_https
|
bool | None
|
Deprecated; use |
None
|
https_port
|
int | None
|
Deprecated; use |
None
|
track_sessions_in_db
|
bool
|
Deprecated; use |
False
|
session_backend
|
str | None
|
Deprecated; use |
None
|
redis_config
|
RedisConfig | dict[str, Any] | None
|
Deprecated; use |
None
|
memcached_config
|
MemcachedConfig | dict[str, Any] | None
|
No longer supported; passing it raises. |
None
|
trusted_proxy_hops
|
int | None
|
Deprecated; use |
None
|
lockout
|
LockoutConfig | None
|
Deprecated; use |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
admin = CRUDAdmin(
session=get_session,
SECRET_KEY=os.environ["ADMIN_SECRET_KEY"],
initial_admin={"username": "admin", "password": os.environ["ADMIN_PASSWORD"]},
)
admin.add_view(model=Product, create_schema=ProductCreate, update_schema=ProductUpdate)
app.mount("/admin", admin.app)
In production, with sessions shared between workers:
admin = CRUDAdmin(
session=get_session,
SECRET_KEY=os.environ["ADMIN_SECRET_KEY"],
admin_db_url="postgresql+asyncpg://user:pass@db/admin",
track_events=True,
sessions=SessionConfig(
backend="redis",
redis=RedisConfig(url=os.environ["REDIS_URL"]),
timeout_minutes=15,
),
access=AccessConfig(
allowed_networks=["10.0.0.0/8"],
enforce_https=True,
trusted_proxy_hops=1,
),
)
Call await admin.initialize() when your app starts and
await admin.shutdown() when it stops, from its lifespan.
Source code in crudadmin/admin_interface/crud_admin.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 | |
session_manager
property
¶
add_view(model, create_schema, update_schema, update_internal_schema=None, delete_schema=None, select_schema=None, include_in_models=True, allowed_actions=None, password_transformer=None, display_field=None)
¶
Add CRUD view for a database model.
Creates a web interface for managing model instances with forms generated from Pydantic schemas.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
type[DeclarativeBase]
|
SQLAlchemy model class to manage |
required |
create_schema
|
type[BaseModel]
|
Pydantic schema for create operations |
required |
update_schema
|
type[BaseModel]
|
Pydantic schema for update operations |
required |
update_internal_schema
|
type[BaseModel] | None
|
Internal schema for special update cases |
None
|
delete_schema
|
type[BaseModel] | None
|
Schema for delete operations |
None
|
select_schema
|
type[BaseModel] | None
|
Optional schema for read operations (excludes fields from queries) |
None
|
include_in_models
|
bool
|
Show in models list in admin UI |
True
|
allowed_actions
|
set[str] | None
|
Set of allowed operations: - "view": Allow viewing records - "create": Allow creating new records - "update": Allow updating existing records - "delete": Allow deleting records Defaults to all actions if None |
None
|
password_transformer
|
Any | None
|
PasswordTransformer instance for handling password field transformation |
None
|
display_field
|
str | None
|
Column used as this model's human-readable label when
it is shown as a related record from another model's view (e.g.
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If schemas don't match model structure |
TypeError
|
If model is not a SQLAlchemy model |
Notes
- Forms are auto-generated with field types determined from Pydantic schemas
- Actions controlled by allowed_actions parameter
- Use select_schema to exclude problematic fields (e.g., TSVector) from read operations
- Use password_transformer for models with password fields that need hashing
URL Routes:
- List view: /admin/
Example
Basic user management:
from pydantic import BaseModel, EmailStr, Field
from typing import Optional
from datetime import datetime
class UserCreate(BaseModel):
username: str = Field(..., min_length=3, max_length=50)
email: EmailStr
role: str = Field(default="user")
active: bool = Field(default=True)
join_date: datetime = Field(default_factory=datetime.utcnow)
class UserUpdate(BaseModel):
email: Optional[EmailStr] = None
role: Optional[str] = None
active: Optional[bool] = None
admin.add_view(
model=User,
create_schema=UserCreate,
update_schema=UserUpdate,
update_internal_schema=None,
delete_schema=None,
allowed_actions={"view", "create", "update"} # No deletion
)
Excluding problematic fields (e.g., TSVector):
class DocumentCreate(BaseModel):
title: str
content: str
# TSVector field excluded from this schema
class DocumentSelect(BaseModel):
id: int
title: str
content: str
created_at: datetime
# search_vector (TSVector) field excluded
admin.add_view(
model=Document,
create_schema=DocumentCreate,
update_schema=DocumentCreate,
select_schema=DocumentSelect, # TSVector field excluded from reads
allowed_actions={"view", "create", "update"}
)
User with password handling:
from crudadmin.admin_interface.model_view import PasswordTransformer
import bcrypt
def hash_password(password: str) -> str:
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
class UserCreateWithPassword(BaseModel):
username: str
email: EmailStr
password: str # This will be transformed to hashed_password
transformer = PasswordTransformer(
password_field="password",
hashed_field="hashed_password",
hash_function=hash_password,
required_fields=["username", "email"]
)
admin.add_view(
model=User,
create_schema=UserCreateWithPassword,
update_schema=UserUpdate,
update_internal_schema=None,
delete_schema=None,
password_transformer=transformer
)
Product catalog with custom validation:
from decimal import Decimal
from pydantic import Field, validator
class ProductCreate(BaseModel):
name: str = Field(..., min_length=2, max_length=100)
price: Decimal = Field(..., ge=0)
description: Optional[str] = Field(None, max_length=500)
category: str
in_stock: bool = True
@validator("price")
def validate_price(cls, v):
if v > 1000000:
raise ValueError("Price cannot exceed 1,000,000")
return v
class ProductUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=2, max_length=100)
price: Optional[Decimal] = Field(None, ge=0)
description: Optional[str] = None
in_stock: Optional[bool] = None
admin.add_view(
model=Product,
create_schema=ProductCreate,
update_schema=ProductUpdate,
update_internal_schema=None,
delete_schema=None,
allowed_actions={"view", "create", "update"}
)
Order management with enum and relationships:
from enum import Enum
from typing import List
class OrderStatus(str, Enum):
pending = "pending"
paid = "paid"
shipped = "shipped"
delivered = "delivered"
cancelled = "cancelled"
class OrderCreate(BaseModel):
user_id: int = Field(..., gt=0)
items: List[int] = Field(..., min_items=1)
shipping_address: str
status: OrderStatus = Field(default=OrderStatus.pending)
notes: Optional[str] = None
class Config:
json_schema_extra = {
"example": {
"user_id": 1,
"items": [1, 2, 3],
"shipping_address": "123 Main St",
"status": "pending"
}
}
class OrderUpdate(BaseModel):
status: Optional[OrderStatus] = None
notes: Optional[str] = None
# Custom delete schema with soft delete
class OrderDelete(BaseModel):
archive: bool = Field(default=False, description="Archive instead of delete")
reason: Optional[str] = Field(None, max_length=200)
admin.add_view(
model=Order,
create_schema=OrderCreate,
update_schema=OrderUpdate,
update_internal_schema=None,
delete_schema=OrderDelete,
allowed_actions={"view", "create", "update", "delete"}
)
Read-only audit log:
class AuditLogSchema(BaseModel):
id: int
timestamp: datetime
user_id: int
action: str
details: dict
class Config:
orm_mode = True
admin.add_view(
model=AuditLog,
create_schema=AuditLogSchema,
update_schema=AuditLogSchema,
update_internal_schema=None,
delete_schema=None,
allowed_actions={"view"}, # Read-only
include_in_models=False # Hide from nav
)
Source code in crudadmin/admin_interface/crud_admin.py
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 | |
get_url_prefix()
¶
initialize()
async
¶
Initialize admin database tables and create initial admin user.
Creates required tables: - AdminUser for user management - AdminSession for session tracking - AdminEventLog and AdminAuditLog if event tracking enabled
Also creates initial admin user if credentials were provided.
Raises:
| Type | Description |
|---|---|
AssertionError
|
If event log models are misconfigured |
ValueError
|
If database initialization fails |
Notes
- This is called automatically if setup_on_initialization=True
- Tables are created with 'checkfirst' to avoid conflicts
- Initial admin is only created if no admin exists
Example
Manual initialization:
Source code in crudadmin/admin_interface/crud_admin.py
setup()
¶
Set up admin interface routes and views.
Configures: - Authentication routes and middleware - Model CRUD views - Management views (health check, events) - Static files
Notes
- Called automatically if setup_on_initialization=True
- Can be called manually after initialization
- Runs once; later calls return without mounting anything again
- Respects allowed_actions configuration
Source code in crudadmin/admin_interface/crud_admin.py
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 | |
shutdown()
async
¶
Close the session stores and the Redis client crudadmin opened.
Call it from your app's lifespan after yield.
Source code in crudadmin/admin_interface/crud_admin.py
Configuration Objects¶
Bases: BaseModel
How admin sessions are kept.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
|
required | |
redis
|
The Redis server for the |
required | |
timeout_minutes
|
Idle time after which a session ends. |
required | |
max_per_admin
|
Sessions an admin may hold at once; logging in again ends the oldest. |
required | |
cleanup_interval_minutes
|
How often expired sessions are swept. |
required | |
secure_cookies
|
Send the session cookies over HTTPS only. Turn off only for local development over plain HTTP. |
required |
Source code in crudadmin/config.py
Bases: BaseModel
Who may reach the admin, and how hard logging in is to guess.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
allowed_ips
|
Client addresses allowed in. With these or
|
required | |
allowed_networks
|
Client networks allowed in, in CIDR notation. |
required | |
enforce_https
|
Redirect plain HTTP requests to HTTPS. |
required | |
https_port
|
The port HTTPS redirects go to. |
required | |
trusted_proxy_hops
|
Reverse proxies in front of the app, whose
|
required | |
lockout
|
Login lockout tuning, a crudauth |
required |