### Install fastapi-amis-admin Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/README.md Install the core library using pip. ```bash pip install fastapi_amis_admin ``` -------------------------------- ### Install python-amis Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/fastapi_amis_admin/amis/README.md Install the python-amis library using pip. This is the first step to using Amis with Python. ```bash pip install amis ``` -------------------------------- ### Install FastAPI-Amis-Admin-Cli Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/tutorials/advanced/cli.md Install the CLI tool using pip. This is the first step before using any of its commands. ```bash pip install fastapi-amis-admin-cli ``` -------------------------------- ### Install fastapi-amis-admin with SQLModel support Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/README.md Install with SQLModel support if you plan to use it for model creation. ```bash pip install fastapi_amis_admin[sqlmodel] ``` -------------------------------- ### Install fastapi-user-auth Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/tutorials/advanced/user-auth.md Install the fastapi-user-auth package using pip. ```bash pip install fastapi-user-auth ``` -------------------------------- ### Install fastapi-scheduler Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/tutorials/advanced/scheduler.md Use this command to install the fastapi-scheduler package. ```bash pip install fastapi-scheduler ``` -------------------------------- ### Async Session Maker Setup Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/utils/database.md Configure a session maker for asynchronous database sessions using `AsyncSession`. ```python self.session_maker: sessionmaker = sessionmaker(self.async_engine, class_=AsyncSession, autoflush=False) ``` -------------------------------- ### Install fastapi-amis-admin Source: https://context7.com/amisadmin/fastapi-amis-admin/llms.txt Install the fastapi-amis-admin package with standard dependencies using pip. ```bash pip install fastapi_amis_admin[standard] ``` -------------------------------- ### Sync Session Maker Setup Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/utils/database.md Configure a session maker for synchronous database sessions. ```python self.session_maker: sessionmaker = sessionmaker(self.async_engine, autoflush=False) ``` -------------------------------- ### Install fastapi-sqlmodel-crud Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/fastapi_amis_admin/crud/README.md Install the fastapi-sqlmodel-crud package using pip. ```bash pip install fastapi-sqlmodel-crud ``` -------------------------------- ### Simple FastAPI SQLModel CRUD Example Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/fastapi_amis_admin/crud/README.md This example demonstrates how to set up a basic CRUD API for an Article model using FastAPI and SQLModel. It includes model definition, database engine creation, CRUD route registration, and table creation on startup. ```python from typing import Optional from fastapi import FastAPI from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine from sqlmodel import SQLModel, Field from fastapi_amis_admin.crud import SqlalchemyCrud # 1. Create SQLModel model class Article(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True, nullable=False) title: str = Field(title='ArticleTitle', max_length=200) description: Optional[str] = Field(default='', title='ArticleDescription', max_length=400) status: bool = Field(None, title='status') content: str = Field(title='ArticleContent') # 2. Create AsyncEngine database_url = 'sqlite+aiosqlite:///amisadmin.db' engine: AsyncEngine = create_async_engine(database_url, future=True) # 3. Register crud route article_crud = SqlalchemyCrud(model=Article, engine=engine).register_crud() app = FastAPI(debug=True) # 4. Include the router app.include_router(article_crud.router) # 5. Create model database table (first run) @app.on_event("startup") async def startup(): async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all) ``` -------------------------------- ### Simple Scheduled Tasks Example Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/tutorials/advanced/scheduler.md This example demonstrates how to create a FastAPI application with scheduled tasks using SchedulerAdmin. It includes interval, cron, and date-based job examples. Ensure the database URL is correctly configured for your needs. ```python from fastapi import FastAPI from fastapi_amis_admin.admin.settings import Settings from fastapi_amis_admin.admin.site import AdminSite from datetime import date from fastapi_scheduler import SchedulerAdmin # Create `FastAPI` application app = FastAPI() # Create `AdminSite` instance site = AdminSite(settings=Settings(database_url_async='sqlite+aiosqlite:///amisadmin.db')) # Create an instance of the scheduled task scheduler `SchedulerAdmin` scheduler = SchedulerAdmin.bind(site) # Add scheduled tasks, refer to the official documentation: https://apscheduler.readthedocs.io/en/master/ # use when you want to run the job at fixed intervals of time @scheduler.scheduled_job('interval', seconds=60) def interval_task_test(): print('interval task is run...') # use when you want to run the job periodically at certain time(s) of day @scheduler.scheduled_job('cron', hour=3, minute=30) def cron_task_test(): print('cron task is run...') # use when you want to run the job just once at a certain point of time @scheduler.scheduled_job('date', run_date=date(2022, 11, 11)) def date_task_test(): print('date task is run...') # Mount the background management system site.mount_app(app) @app.on_event("startup") async def startup(): # Start the scheduled task scheduler scheduler.start() if __name__ == '__main__': import uvicorn uvicorn.run(app) ``` -------------------------------- ### Simple HTML Template Example Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/tutorials/basic/TemplateAdmin.md An example of a basic HTML file that can be rendered by TemplateAdmin. It includes a placeholder for dynamic data like the current time. ```html Current Time

Current Time

The current time is: {{ current_time }}

``` -------------------------------- ### FastAPI-Amis-Admin CLI Commands Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/index.md Install the command-line extension and use `faa` to initialize new projects or applications. ```bash # Install command line extension pip install fastapi_amis_admin[cli] # View help faa --help # Initialize a `FastAPI-Amis-Admin` project faa new project_name --init # Initialize a `FastAPI-Amis-Admin` application faa new app_name ``` -------------------------------- ### Create FastAPI Application and AdminSite Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/README.md Basic setup for a FastAPI application with an AdminSite instance. Mounts the AdminSite to the FastAPI app. ```python from fastapi import FastAPI from fastapi_amis_admin.admin.settings import Settings from fastapi_amis_admin.admin.site import AdminSite # create FastAPI application app = FastAPI() # create AdminSite instance site = AdminSite(settings=Settings(database_url_async='sqlite+aiosqlite:///amisadmin.db')) # mount AdminSite instance site.mount_app(app) if __name__ == '__main__': import uvicorn uvicorn.run(app) ``` -------------------------------- ### Install FastAPI Amis Admin CLI Source: https://context7.com/amisadmin/fastapi-amis-admin/llms.txt Install the CLI extension using pip to enable project scaffolding and development server commands. ```bash pip install fastapi_amis_admin[cli] ``` -------------------------------- ### FastAPI-Amis-Admin CLI Commands Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/README.md Install and use the FastAPI-Amis-Admin command-line interface for project initialization, app creation, and running the development server. ```bash # Install command line extension pip install fastapi_amis_admin[cli] # View help faa --help # Initialize a `FastAPI-Amis-Admin` project faa new project_name --init # Initialize a `FastAPI-Amis-Admin` application faa new app_name # Fast running project faa run ``` -------------------------------- ### Run FastAPI Amis Admin Development Server Source: https://context7.com/amisadmin/fastapi-amis-admin/llms.txt Start the development server for your FastAPI Amis Admin project. ```bash faa run ``` -------------------------------- ### Configure AdminSite with Basic Settings Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/tutorials/basic/Settings.md Initialize AdminSite with basic settings like debug mode and asynchronous database URL. This example also configures FastAPI application settings such as debug mode and API documentation paths. ```python from fastapi import FastAPI from fastapi_amis_admin.admin.settings import Settings from fastapi_amis_admin.admin.site import AdminSite site = AdminSite( # 基本配置 settings=Settings(debug=True, database_url_async='sqlite+aiosqlite:///amisadmin.db'), # fastapi相关配置 fastapi=FastAPI(debug=True, docs_url='/admin_docs', redoc_url='/admin_redoc') ) ``` -------------------------------- ### Define Base SQLModel Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/README.md Example of creating a base model using SQLModel, which can be extended for other models. ```python from typing import Optional from sqlmodel import SQLModel from fastapi_amis_admin.models.fields import Field class Base(SQLModel): pass ``` -------------------------------- ### Get Create Form Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/amis_admin/ModelAdmin.md Returns the form configuration for creating new model data. Supports both single and bulk creation scenarios. ```python async def get_create_form(self, request: Request, bulk: bool = False) -> Form ``` -------------------------------- ### Define a Login Form with FastAPI Amis Admin Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/tutorials/basic/FormAdmin.md This example demonstrates how to create a login form using `FormAdmin`. It includes defining the form's schema with Pydantic, specifying form configuration, and implementing the submission handling logic. ```python from fastapi_amis_admin.admin import admin from fastapi_amis_admin.crud import BaseApiOut from fastapi_amis_admin.models.fields import Field from pydantic import BaseModel from starlette.requests import Request @site.register_admin class UserLoginFormAdmin(admin.FormAdmin): page_schema = 'UserLoginForm' # Configure form information, can be omitted form = Form(title='This is a test login form', submitText='Login') # Create a form data model class schema(BaseModel): username: str = Field(... , title='username', min_length=3, max_length=30) password: str = Field(... , title='password') # Handle form submission data async def handle(self, request: Request, data: BaseModel, **kwargs) -> BaseApiOut[Any]: if data.username == 'amisadmin' and data.password == 'amisadmin': return BaseApiOut(msg='Login successful!' , data={'token': 'xxxxxxx'}) return BaseApiOut(status=-1, msg='Username or password error!') ``` -------------------------------- ### Get Initialization Data in FormAdmin Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/amis_admin/FormAdmin.md Retrieves initialization data for a form page. Accepts a Request object and returns a BaseApiOut object. ```python async def get_init_data(self, request: Request, **kwargs) -> BaseApiOut[Any] ``` -------------------------------- ### Get Create Action Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/amis_admin/ModelAdmin.md Returns the Amis Action object for the create data action. Supports bulk creation. Refer to Amis Action documentation. ```python async def get_create_action(self, request: Request, bulk: bool = False) -> Optional[Action] ``` -------------------------------- ### Create SQLAlchemy Category Table on Startup Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/tutorials/basic/ModelAdmin.md Configure the FastAPI application to create the 'category' database table when the application starts. This ensures the table exists before any database operations. ```python @app.on_event("startup") async def startup(): await site.db.async_run_sync(Category.metadata.create_all, is_session=False) pass ``` -------------------------------- ### Create AdminSite Instance and Register Admin Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/tutorials/quickstart.md This Python code sets up an AdminSite instance with a database connection and registers a GitHubIframeAdmin class to display an iframe. ```python from fastapi_amis_admin.admin.settings import Settings from fastapi_amis_admin.admin.site import AdminSite from fastapi_amis_admin.admin import admin from fastapi_amis_admin.amis.components import PageSchema # Create AdminSite instance site = AdminSite(settings=Settings(database_url_async='sqlite+aiosqlite:///amisadmin.db')) # Registration management class @site.register_admin class GitHubIframeAdmin(admin.IframeAdmin): # Set page menu information page_schema = PageSchema(label='AmisIframeAdmin', icon='fa fa-github') # Set the jump link src = 'https://github.com/amisadmin/fastapi_amis_admin' ``` -------------------------------- ### Define Database Models with SQLModel Source: https://context7.com/amisadmin/fastapi-amis-admin/llms.txt Define database models for Category and Article using SQLModel, including fields, constraints, and relationships. This setup is for persistence with a SQLite database. ```python from typing import Optional from fastapi import FastAPI from sqlmodel import Field, SQLModel from contextlib import asynccontextmanager from fastapi_amis_admin.admin.site import AdminSite from fastapi_amis_admin.admin import admin from fastapi_amis_admin.admin.settings import Settings from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.future import select from sqlalchemy import Select from starlette.requests import Request class Category(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True, nullable=False) name: str = Field(title='Category Name', max_length=100, unique=True, index=True) description: str = Field(default='', title='Description', max_length=255) class Article(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True, nullable=False) title: str = Field(title='Article Title', max_length=200) description: Optional[str] = Field(default='', title='Article Description', max_length=400) status: bool = Field(default=False, title='Published') content: str = Field(title='Article Content') category_id: Optional[int] = Field(default=None, foreign_key="category.id", title='Category') @asynccontextmanager async def lifespan(app: FastAPI): # Create database tables on startup await site.db.async_run_sync(SQLModel.metadata.create_all, is_session=False) yield app = FastAPI(lifespan=lifespan) site = AdminSite(settings=Settings(database_url_async="sqlite+aiosqlite:///blog.db")) @site.register_admin class CategoryAdmin(admin.ModelAdmin): page_schema = 'Categories' model = Category # Display CRUD actions as columns instead of dropdown display_item_action_as_column = True @site.register_admin class ArticleAdmin(admin.ModelAdmin): page_schema = 'Articles' model = Article # Display specific fields including related model field list_display = [Article.id, Article.title, Article.status, Category.name] # Enable fuzzy search on these fields search_fields = [Article.title, Category.name] # Fields that can be bulk edited bulk_update_fields = [Article.status] # Items per page list_per_page = 20 # Custom selector to join Category table async def get_select(self, request: Request) -> Select: stmt = await super().get_select(request) return stmt.outerjoin(Category, Article.category_id == Category.id) site.mount_app(app) if __name__ == "__main__": import uvicorn uvicorn.run(app) ``` -------------------------------- ### Initialize FastAPI-Amis-Admin Project Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/tutorials/advanced/structure.md Use this command to generate a new FastAPI-Amis-Admin project structure. ```bash faa new project_name --init ``` -------------------------------- ### Initialize BaseAdminSite Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/amis_admin/AdminSite.md Initializes the management site with settings, a FastAPI application, and an optional database engine. ```python def __init__(self, settings: Settings, fastapi: FastAPI = None, engine: AsyncEngine = None) ``` -------------------------------- ### Basic AdminSite Initialization Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/tutorials/basic/Settings.md Initialize AdminSite with basic settings including debug mode and asynchronous database URL, and configure FastAPI application with custom documentation paths. ```python from fastapi import FastAPI from fastapi_amis_admin.admin.settings import Settings from fastapi_amis_admin.admin.site import AdminSite site = AdminSite( # Basic configuration settings=Settings(debug=True, database_url_async='sqlite+aiosqlite:///amisadmin.db'), # fastapi related configuration fastapi=FastAPI(debug=True, docs_url='/admin_docs', redoc_url='/admin_redoc') ) ``` -------------------------------- ### Initialize New FastAPI Amis Admin Project Source: https://context7.com/amisadmin/fastapi-amis-admin/llms.txt Scaffold a new FastAPI Amis Admin project with the `--init` flag to set up the basic project structure. ```bash faa new my_project --init ``` -------------------------------- ### Initialize Alembic Migrations Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/extended/alembic.md Run this command once to create the initial migrations folder for your project. Use the '-t async' flag for asynchronous support. ```bash alembic init -t async migrations ``` -------------------------------- ### Create Admin Site with FastAPI Source: https://context7.com/amisadmin/fastapi-amis-admin/llms.txt Create a FastAPI application and an AdminSite instance with settings for an async SQLite database. Mount the admin site to the FastAPI app. ```python from fastapi import FastAPI from fastapi_amis_admin.admin.settings import Settings from fastapi_amis_admin.admin.site import AdminSite # Create FastAPI application app = FastAPI() # Create AdminSite with async SQLite database site = AdminSite( settings=Settings( debug=True, site_title="My Admin Dashboard", database_url_async='sqlite+aiosqlite:///amisadmin.db' ) ) # Mount admin site to FastAPI app at /admin path site.mount_app(app) if __name__ == '__main__': import uvicorn uvicorn.run(app, host="127.0.0.1", port=8000) # Access admin at: http://127.0.0.1:8000/admin/ # Access API docs at: http://127.0.0.1:8000/admin/docs ``` -------------------------------- ### Get Route Page Callable Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/amis_admin/PageAdmin.md This property returns the callable for the page route. ```python @property def route_page(self) -> Callable: ``` -------------------------------- ### Get List Filter Form Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/amis_admin/ModelAdmin.md Returns the Amis Form object for the list filter. ```python async def get_list_filter_form(self, request: Request) -> Form ``` -------------------------------- ### Create a Static 'Hello World' Page Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/tutorials/basic/PageAdmin.md Define a simple static page using `PageAdmin` and `Page` component. This is suitable for displaying fixed content. ```python from fastapi_amis_admin.admin import admin from fastapi_amis_admin.amis.components import Page @site.register_admin class HelloWorldPageAdmin(admin.PageAdmin): page_schema = 'Hello World Page' # 通过page类属性直接配置页面信息; page = Page(title='标题', body='Hello World!') ``` -------------------------------- ### Get Link Model Forms Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/amis_admin/ModelAdmin.md Returns a list of forms for linked many-to-many model fields. ```python def get_link_model_forms(self) -> List[LinkModelForm] ``` -------------------------------- ### Get List Filter API Configuration Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/amis_admin/ModelAdmin.md Returns the AmisAPI object for the list filter form. ```python async def get_list_filter_api(self, request: Request) -> AmisAPI ``` -------------------------------- ### Get List Columns Configuration Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/amis_admin/ModelAdmin.md Returns a list of Amis TableColumn objects for all table columns. ```python async def get_list_columns(self, request: Request) -> List[TableCRUD.Column] ``` -------------------------------- ### Get Specific Child Page Schema Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/amis_admin/AdminGroup.md Retrieves a specific child page schema by its unique identifier. ```python def get_page_schema_child(self, unique_id: str) -> Optional[_PageSchemaAdminT] ``` -------------------------------- ### Initialize FastAPI-Amis-Admin Application Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/tutorials/advanced/structure.md Use this command to generate a new application within an existing FastAPI-Amis-Admin project. ```bash faa new app_name ``` -------------------------------- ### Create SQLAlchemy Article Table on Startup Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/tutorials/basic/ModelAdmin.md Append the command to create the 'article' database table to the application's startup event. This ensures the table is created along with other necessary tables. ```python await site.db.async_run_sync(Article.metadata.create_all, is_session=False) ``` -------------------------------- ### Get Page Schema Information Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/amis_admin/PageSchemaAdmin.md Returns the navigation information for the current page. If None, it will not be displayed in the menu navigation. ```python def get_page_schema(self) -> Optional[PageSchema] ``` -------------------------------- ### Get Page Context Dictionary Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/amis_admin/TemplateAdmin.md Retrieves the context dictionary for the current page. This method is part of the TemplateAdmin class. ```python async def get_page(self, request: Request) -> Dict[str, Any] ``` -------------------------------- ### Get Update Form Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/amis_admin/ModelAdmin.md Returns the Amis Form object for updating existing model data. Supports bulk updates. ```python async def get_update_form(self, request: Request, bulk: bool = False) -> Form ``` -------------------------------- ### FastAPI Amis Admin CLI Help Source: https://context7.com/amisadmin/fastapi-amis-admin/llms.txt View the help documentation for the FastAPI Amis Admin CLI to understand available commands and options. ```bash faa --help ``` -------------------------------- ### Get Create Form Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/amis_admin/ModelAdmin.md Returns the Amis Form object for creating new model data. Supports bulk creation. ```python async def get_create_form(self, request: Request, bulk: bool = False) -> Form ``` -------------------------------- ### Basic FastAPI App with AuthAdminSite Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/tutorials/advanced/user-auth.md Set up a FastAPI application with AuthAdminSite for user authentication. This includes database configuration, mounting the admin site, and initializing tables with default users. ```python from fastapi import FastAPI from fastapi_amis_admin.admin import Settings from fastapi_user_auth.site import AuthAdminSite from sqlmodel import SQLModel # Create FastAPI application app = FastAPI() # Create AdminSite instance site = AuthAdminSite( settings=Settings(database_url_async='sqlite+aiosqlite:///amisadmin.db') ) auth = site.auth # Mount the background management system site.mount_app(app) # Create initialized database table @app.on_event("startup") async def startup(): await site.db.async_run_sync(SQLModel.metadata.create_all,is_session=False) # Create a default test user, please change the password in time!!! await auth.create_role_user('admin') await auth.create_role_user('vip') if __name__ == '__main__': import uvicorn uvicorn.run(app) ``` -------------------------------- ### Get Actions by Flag Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/amis_admin/ModelAdmin.md Returns a list of Amis Action objects based on the specified flag (item, bulk, toolbar, column). ```python async def get_actions(self, request: Request, flag:str) -> List[Action] ``` -------------------------------- ### Get List Table Configuration Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/amis_admin/ModelAdmin.md Returns the Amis TableCRUD object for the page. Refer to Amis CRUD and Table documentation for details. ```python async def get_list_table(self, request: Request) -> TableCRUD ``` -------------------------------- ### Generate Initial Migration File Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/extended/alembic.md Execute this command to automatically generate the initial migration script based on your SQLModel definitions. ```bash alembic revision --autogenerate ``` -------------------------------- ### Get Amis Page Object Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/amis_admin/PageAdmin.md Asynchronously retrieves the Amis Page object. It takes a Request object and returns a Page instance. ```python async def get_page(self, request: Request) -> Page: ``` -------------------------------- ### Implement a User Login Form with FormAdmin Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/tutorials/basic/FormAdmin.md This example demonstrates how to create a login form using `FormAdmin`. It defines the form's schema with username and password fields and implements a `handle` method to process login credentials. The form is registered with the admin site. ```python from fastapi_amis_admin.admin import admin from fastapi_amis_admin.crud import BaseApiOut from fastapi_amis_admin.models.fields import Field from pydantic import BaseModel from starlette.requests import Request from fastapi_amis_admin.amis import Form from typing import Any @site.register_admin class UserLoginFormAdmin(admin.FormAdmin): page_schema = 'UserLoginForm' # 配置表单信息, 可省略 form = Form(title='这是一个测试登录表单', submitText='登录') # 创建表单数据模型 class schema(BaseModel): username: str = Field(..., title='用户名', min_length=3, max_length=30) password: str = Field(..., title='密码') # 处理表单提交数据 async def handle(self, request: Request, data: BaseModel, **kwargs) -> BaseApiOut[Any]: if data.username == 'amisadmin' and data.password == 'amisadmin': return BaseApiOut(msg='登录成功!', data={'token': 'xxxxxx'}) return BaseApiOut(status=-1, msg='用户名或密码错误!') ``` -------------------------------- ### Generate SQLModel Initialization Migration Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/extended/alembic.md Execute this command to generate the initial migration file based on your SQLModel schema. This is typically done after setting up the models and Alembic. ```bash alembic revision --autogenerate ``` -------------------------------- ### Get Update Form Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/amis_admin/ModelAdmin.md Returns the form configuration for updating existing model data. Supports both single and bulk update scenarios. ```python async def get_update_form(self, request: Request, bulk: bool = False) -> Form ``` -------------------------------- ### 注册全局权限验证依赖 Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/tutorials/advanced/permission.md 通过向 FastAPI 实例的 dependencies 添加 Depends 对象,可以为 AdminSite 下的所有路由注册全局权限验证。 ```python from fastapi import Depends, FastAPI, Header, HTTPException async def verify_token(x_token: str = Header(...)): if x_token != "fake-super-secret-token": raise HTTPException(status_code=400, detail="X-Token header invalid") site = AdminSite( settings=Settings(debug=True, database_url_async='sqlite+aiosqlite:///amisadmin.db'), fastapi=FastAPI(dependencies=[Depends(verify_token)]) ) ``` -------------------------------- ### Get Link Model Forms Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/amis_admin/ModelAdmin.md Returns a list of form configurations for many-to-many associated fields. This is used when managing relationships between models. ```python def get_link_model_forms(self) -> List[LinkModelForm] ``` -------------------------------- ### Get Amis TableCRUD Object Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/amis_admin/ModelAdmin.md Returns the Amis TableCRUD object for the page. This is the main configuration for the data table displayed to the user. ```python async def get_list_table(self, request: Request) -> TableCRUD ``` -------------------------------- ### Get List Display Fields Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/amis_admin/ModelAdmin.md Returns the list of fields to be displayed in the table list. This method can be overridden to customize the displayed columns. ```python async def get_list_display( self, request: Request ) -> List[Union[SQLModelListField, TableCRUD.Column]] ``` -------------------------------- ### Registering Global Permission Verification Dependency Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/tutorials/advanced/permission.md Demonstrates how to apply a global permission check to all routes under an `AdminSite` instance. ```APIDOC ## Registering Global Permission Verification Dependency By registering a global permission verification dependency, all routes under the `AdminSite` object will require passing the specified permission check. ```python from fastapi import Depends, FastAPI, Header, HTTPException async def verify_token(x_token: str = Header(...)): if x_token != "fake-super-secret-token": raise HTTPException(status_code=400, detail="X-Token header invalid") site = AdminSite( settings=Settings(debug=True, database_url_async='sqlite+aiosqlite:///amisadmin.db'), fastapi=FastAPI(dependencies=[Depends(verify_token)]) ) ``` ``` -------------------------------- ### Custom AdminSite with New Template and Branding Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/tutorials/basic/Settings.md Create a custom admin site by inheriting from AdminSite, specifying a custom template, unregistering default documentation classes, and customizing the site's brand name and logo. ```python from fastapi import FastAPI, Request from fastapi_amis_admin.admin.settings import Settings from fastapi_amis_admin.admin.site import AdminSite, ReDocsAdmin, DocsAdmin from sqlalchemy.ext.asyncio import AsyncEngine from fastapi_amis_admin.amis.components import App # Custom backend administration site class NewAdminSite(AdminSite): # custom application template, copy the original template file to modify the original path: fastapi_amis_admin/amis/templates/app.html template_name = '/templates/new_app.html' def __init__(self, settings: Settings, fastapi: FastAPI = None, engine: AsyncEngine = None): super(). __init__(settings, fastapi, engine) # Unregister the default admin class self.unregister_admin(DocsAdmin, ReDocsAdmin) async def get_page(self, request: Request) -> App: app = await super().get_page(request) # Custom site name, logo information, reference: https://baidu.gitee.io/amis/zh-CN/components/app app.brandName = 'MyAdminSite' app.logo = 'https://baidu.gitee.io/amis/static/logo_408c434.png' return app # Create a backend management system instance with a custom admin site class site = NewAdminSite(settings=Settings(debug=True, database_url_async='sqlite+aiosqlite:///amisadmin.db')) ``` -------------------------------- ### Get Current APIRouter in FastAPI Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/crud/RouterMixin.md Returns the current APIRouter instance managed by the RouterMixin. This is useful for accessing or modifying router configurations. ```python def get_router(self) -> APIRouter ``` -------------------------------- ### Create a Simple Hello World Page Admin Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/tutorials/basic/PageAdmin.md Define a PageAdmin to display a static 'Hello World' page. Configure page information directly through the page class property. ```python from fastapi_amis_admin.admin import admin from fastapi_amis_admin.amis import Page @site.register_admin class HelloWorldPageAdmin(admin.PageAdmin): page_schema = 'Hello World Page' # Configure page information directly through the page class property; page = Page(title='Title', body='Hello World!') ``` -------------------------------- ### Create a Simple Amis Page Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/fastapi_amis_admin/amis/README.md Demonstrates how to create a basic Amis page using the Page component and output its Amis JSON, dictionary, or HTML representation. Ensure you have the necessary imports. ```python from amis.components import Page page = Page(title='title', body='Hello World!') # output as json print(page.amis_json()) # output as dict print(page.amis_dict()) # output page html print(page.amis_html()) ``` -------------------------------- ### Get Form Object in BaseFormAdmin Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/amis_admin/FormAdmin.md Retrieves the current page's Amis Form object. This method is part of the BaseFormAdmin class. ```python async def get_form(self, request: Request) -> Form ``` -------------------------------- ### Get Specific Action by Name Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/amis_admin/ModelAdmin.md Returns a specific Amis Action object by its unique name. The name corresponds to actions returned by `get_actions`. ```python async def get_action(self, request: Request, name: str) -> Action ``` -------------------------------- ### FastAPI-Amis-Admin CLI Quick Usage Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/tutorials/advanced/cli.md Common commands for interacting with the CLI, including viewing help, initializing projects and applications, and running the project. ```bash ## View help faa --help ``` ```bash # Initialize a `FastAPI-Amis-Admin` project faa new project_name --init ``` ```bash # Initialize a `FastAPI-Amis-Admin` application faa new app_name ``` ```bash # Run the project quickly faa run ``` -------------------------------- ### Get List Filter Fields Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/amis_admin/ModelAdmin.md Returns the list of fields for the filter form in the table. Supports Amis FormItem and SQLAlchemy Label types. ```python async def get_list_filter(self, request: Request) -> List[Union[SQLModelListField, FormItem]] ``` -------------------------------- ### FastAPI-Amis-Admin CLI Usage Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/zh/docs/tutorials/advanced/cli.md Common commands for the FastAPI-Amis-Admin-Cli, including viewing help, initializing new projects or applications, and running the project. ```bash faa --help ``` ```bash faa new project_name --init ``` ```bash faa new app_name ``` ```bash faa run ``` -------------------------------- ### Run the FastAPI Application Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/tutorials/quickstart.md Use the uvicorn command to run the FastAPI application defined in main.py. ```bash uvicorn main:app ``` -------------------------------- ### Get Update Action Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/amis_admin/ModelAdmin.md Returns the Amis Action object for updating model data. This defines the action triggered when an update operation is performed. ```python async def get_update_action(self, request: Request, bulk: bool = False) -> Optional[Action] ``` -------------------------------- ### Get List Filter API Source: https://github.com/amisadmin/fastapi-amis-admin/blob/master/docs/en/docs/amis_admin/ModelAdmin.md Provides the AmisAPI object for the list filter form. This defines how the filter form data is fetched and submitted. ```python async def get_list_filter_api(self, request: Request) -> AmisAPI ```