fastapi_amis_admin 是一个功能强大的框架,旨在帮助开发者在使用 FastAPI 进行 web 开发时,能够快速创建一个高效且易于管理的后台界面。通过结合 FastAPI 和 amis 的优势,fastapi_amis_admin 提供了一种简洁而高效的方式来构建和管理 web 应用程序的后台。
主要特性:
高性能:基于 FastAPI,保证了高并发和快速响应的能力。
高效率:通过 amis 实现快速构建可视化界面,减少开发时间。
易于使用:基于标准的 Python 类型提示,简化开发流程。
开源免费:遵循 Apache2.0 协议,鼓励社区参与和贡献。
具体用法:
- 安装:
首先,确保你的 Python 版本是 3.6 或更高。然后,使用 pip 进行安装:
bash
pip install fastapi_amis_admin
2. 创建 FastAPI 应用:
如果你还没有一个 FastAPI 项目,可以先创建一个:
python
from fastapi import FastAPI
app = FastAPI()
3. 定义你的数据模型:
例如,如果你有一个用户模型:
python
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
email: str
4. 使用 fastapi_amis_admin 快速生成管理后台:
python
from fastapi_amis_admin import AdminSite, ModelAdmin
from your_models import User # 引入你刚定义的数据模型
admin_site = AdminSite(app) # 创建一个 AdminSite 实例
注册你的数据模型到 AdminSite 中
admin_site.register(ModelAdmin(User))
5. 启动你的 FastAPI 应用:
使用 UVicorn 或其他你喜欢的 ASGI 服务器来运行你的应用。例如,使用 UVicorn:
bash
uvicorn main:app --reload # ‘main’ 是你的主模块名,‘app’ 是你的 FastAPI 实例名
6. 访问管理后台:
默认情况下,后台管理界面会在 /admin 路径下生成。你可以在浏览器中访问 http://localhost:8000/admin 来查看和使用管理后台。使用你定义的模型名称(例如,“User”)作为菜单项来管理相应的数据。
pip install fastapi_amis_admin[cli]
pip install pydantic[dotenv]
# View help
faa --help
# Initialize a `FastAPI-Amis-Admin` project
faa new music --init
# Initialize a `FastAPI-Amis-Admin` application
faa new music
# Fast running project
faa run
再回顾:
uvicorn>=0.18.3
pydantic[dotenv]>=1.9.0
aiosqlite>=0.17.0
fastapi-amis-admin>=0.5.0,<0.6.0
fastapi-user-auth>=0.5.0,<0.6.0
fastapi-scheduler>=0.0.6,<0.1.0
aiomysql
fastapi-config
aioredis
celery
flower
在这里我们让项目支持redis 以及rabbitmq
##创建一个项目如下图:
##rabbitmq的配置:
#!/usr/bin/python3
# !--*-- coding: utf-8 --*--
import time
from celery import Celery
from celery.utils.log import get_task_logger
# 实例化 Celery
celery = Celery('tasks', broker='amqp://wanghaibin:wanghaibin@127.0.0.1:5672//')
# 创建 logger,以显示日志信息
celery_log = get_task_logger(__name__)
# 创建任务函数,以订单(Order) 为例,异步进行
@celery.task
def create_order(name, quantity):
# 5 seconds per 1 order
complete_time_per_item = 5
# Keep increasing depending on item quantity being ordered
time.sleep(complete_time_per_item * quantity)
# 显示日志
celery_log.info(f"Order Complete!")
return {"message": f"Hi {name}, Your order has completed!",
"order_quantity": quantity}
#!/usr/bin/python3
#!--*-- coding: utf-8 --*--
from pydantic import BaseModel
# Pydantic BaseModel
# Order class model for request body
class Order(BaseModel):
customer_name: str
order_quantity: int
##再看music
models.py创建了表:
from datetime import datetime
from typing import List, Optional
import sqlmodel
from fastapi_amis_admin.amis.components import ColumnImage, InputImage, InputRichText
from fastapi_amis_admin.models.enums import IntegerChoices
from fastapi_amis_admin.models.fields import Field
from fastapi_user_auth.auth.models import PkMixin, User
from sqlalchemy import Column, String, select
from sqlalchemy.orm import Session
class ArticleStatus(IntegerChoices):
unpublished = 0, "未发布"
published = 1, "已发布"
inspection = 2, "审核中"
disabled = 3, "已禁用"
class Category(PkMixin, table=True):
__tablename__ = "category"
name: str = Field(title="歌曲分类名", sa_column=Column(String(100), unique=True, index=True, nullable=False))
description: str = Field(default="", title="描述", amis_form_item="textarea")
status: bool = Field(False, title="状态")
articles: List["Article"] = sqlmodel.Relationship(back_populates="category")
class ArticleTagLink(sqlmodel.SQLModel, table=True):
__tablename__ = "music_tags"
tag_id: Optional[int] = Field(default=None, foreign_key="tag.id", primary_key=True)
music_id: Optional[int] = Field(default=None, foreign_key="article.id", primary_key=True)
class Tag(PkMixin, table=True):
__tablename__ = "tag"
name: str = Field(..., title="标签名", sa_column=Column(String(255), unique=True, index=True, nullable=False))
articles: List["Article"] = sqlmodel.Relationship(back_populates="tags", link_model=ArticleTagLink)
class Article(PkMixin, table=True):
__tablename__ = "article"
title: str = Field(title="歌曲名", max_length=200)
img: str = Field(
None,
title="图片",
max_length=300,
amis_form_item=InputImage(maxLength=1, maxSize=2 * 1024 * 1024, receiver="post:/admin/file/upload"),
amis_table_column=ColumnImage(width=100, height=60, enlargeAble=True),
)
url: str = Field(default="", title="mp3 url", amis_form_item="textarea")
status: ArticleStatus = Field(ArticleStatus.unpublished, title="status")
content: str = Field(..., title="说明", amis_form_item=InputRichText())
create_time: Optional[datetime] = Field(default_factory=datetime.utcnow, title="增加时间")
source: str = Field(default="", title="来源", max_length=200)
category_id: Optional[int] = Field(default=None, foreign_key="category.id", title="分类")
category: Optional[Category] = sqlmodel.Relationship(back_populates="articles")
tags: List[Tag] = sqlmodel.Relationship(back_populates="articles", link_model=ArticleTagLink)
user_id: int = Field(default=None, foreign_key="auth_user.id", title="用户")
user: User = sqlmodel.Relationship()
@staticmethod
def check_update_permission(session: Session, user: User, item_id: List[str]):
# 管理员可以修改全部文章, 并且可以批量修改.
if user.has_requires(session, roles=["admin"]):
return True
# 非管理员,只能修改自己的文章,并且不可批量修改.
if len(item_id) > 1:
return False
stmt = select(1).where(Article.id == item_id[0], Article.user_id == user.id)
return bool(session.scalar(stmt))
admin.py表现的是菜单的链接
from datetime import datetime, timedelta
from typing import Any, Dict, List
from apps.music.models import Article, Category, Tag
from core.adminsite import site
from fastapi_amis_admin import admin
from fastapi_amis_admin.admin import AdminApp, PageSchemaAdmin
from fastapi_amis_admin.amis.components import PageSchema, TableColumn
from fastapi_amis_admin.crud.parser import LabelField, PropertyField
from fastapi_amis_admin.crud.schema import Paginator
from fastapi_amis_admin.models import Field
from fastapi_user_auth.auth.models import User
from pydantic import BaseModel
from sqlmodel.sql.expression import Select
from starlette.requests import Request
@site.register_admin
class BlogApp(admin.AdminApp):
page_schema = PageSchema(label="音乐管理", icon="fa fa-calculator")
router_prefix = "/music"
def __init__(self, app: "AdminApp"):
super().__init__(app)
self.register_admin(ArticleAdmin,CategoryAdmin, TagAdmin)
class CategoryAdmin(admin.ModelAdmin):
page_schema = PageSchema(label="音乐分类管理", icon="fa fa-folder")
model = Category
search_fields = [Category.name]
class TagAdmin(admin.ModelAdmin):
page_schema = PageSchema(label="音乐标签管理", icon="fa fa-tags")
model = Tag
search_fields = [Tag.name]
link_model_fields = [Tag.articles]
class ArticleAdmin(admin.ModelAdmin):
page_schema = PageSchema(label="音乐管理", icon="fa fa-file")
model = Article
# 配置列表展示字段
list_display = [
#TableColumn(type="tpl", label="自定义模板列", tpl='<a href="${source}" target="_blank">ID:${id},Title:${title}</a>'),
Article.id,
Article.title.label("歌名"),
Article.img,
Category.name,
User.username,
Article.create_time,
Article.url,
User.nickname.label("昵称"), # 重命名字段;也可以使用sqlalchemy函数, 例如:
#func.count('*').label('music_count'), #注意在`get_select`中修改对应的sql查询语句
LabelField(
User.nickname.label("nickname2"),
Field("默认用户", title="发布者"), # 通过Field配置Amis表格列信息,Amis表单字段信息.
),
]
# 配置模糊搜索字段
search_fields = [Article.title, Category.name, User.username]
# 配置关联模型
link_model_fields = [Article.tags]
# 读取查看表单字段
read_fields = [
Article,
PropertyField(name="category", type_=Category),
PropertyField(name="user", type_=User),
PropertyField(name="tags", type_=List[Tag]),
]
# 自定义查询选择器
async def get_select(self, request: Request) -> Select:
sel = await super().get_select(request)
return sel.join(Category, isouter=True).join(User, isouter=True)
# 权限验证
async def has_page_permission(self, request: Request, obj: PageSchemaAdmin = None, action: str = None) -> bool:
return True
async def has_list_permission(self, request: Request, paginator: Paginator, filters: BaseModel = None, **kwargs) -> bool:
# 用户未登录,不可按标题过滤文章,并且最多每页最多只能查看10条数据.
return bool(await self.site.auth.requires(response=False)(request) or (paginator.perPage <= 10 and filters.title == ""))
async def has_create_permission(self, request: Request, data: BaseModel, **kwargs) -> bool:
# 用户已登录,并且注册时间大于3天,才可以发布文章
return bool(
await self.site.auth.requires(response=False)(request)
and request.user.create_time < datetime.now() - timedelta(days=3)
) or await self.site.auth.requires(roles="admin", response=False)(request)
async def has_delete_permission(self, request: Request, item_id: List[str], **kwargs) -> bool:
# 必须管理员才可以删除文章.
return await self.site.auth.requires(roles="admin", response=False)(request)
async def has_update_permission(self, request: Request, item_id: List[str], data: BaseModel, **kwargs) -> bool:
if not await self.site.auth.requires(response=False)(request):
return False
if item_id is None:
return True
return await self.site.db.async_run_sync(Article.check_update_permission, request.user, item_id)
async def on_create_pre(self, request: Request, obj: BaseModel, **kwargs) -> Dict[str, Any]:
data = await super().on_create_pre(request, obj, **kwargs)
# 创建新文章时,设置当前用户为发布者
data["user_id"] = request.user.id
return data
main.py代码:
from starlette.responses import RedirectResponse
from fastapi import FastAPI
from core.adminsite import site
from core.settings import settings
from sqlmodel import SQLModel
from aioredis import create_redis_pool, Redis
from apps.rabbitmq.model import Order
from apps.rabbitmq.celery_worker import create_order
app = FastAPI(debug=settings.debug)
# 安装应用
from apps import admin
admin.setup(app.router, site)
# 安装应用blog
from apps import music
music.setup(app)
from apps import siteconfig
siteconfig.setup(app)
# from apps import project
# project.setup(app)
# 挂载后台管理系统
site.mount_app(app)
@app.get('/')
async def index():
return RedirectResponse(url=site.router_path)
@app.on_event("startup")
async def startup():
from core.adminsite import auth
await site.db.async_run_sync(SQLModel.metadata.create_all, is_session=False)
await auth.create_role_user('admin')
app.state.redis = await get_redis_pool()
from core.adminsite import scheduler
scheduler.start()
async def get_redis_pool() -> Redis: #redis
redis = await create_redis_pool(f"redis://:@127.0.0.1:6379/0?encoding=utf-8")
return redis
@app.on_event("shutdown")
async def shutdown_event():
app.state.redis.close()
await app.state.redis.wait_closed()
@app.post('/order')
def add_order(order: Order):
create_order.delay(order.customer_name, order.order_quantity)
return {"message": "Order Received! Thank you for your patience."}
这里还有一个core的目录。主要是解决数据据的配置
setting.py
import os
from pathlib import Path
from typing import List
from fastapi_amis_admin.admin.settings import Settings as AmisSettings
BASE_DIR = Path(__file__).resolve().parent.parent
class Settings(AmisSettings):
name: str = 'JJSOS'
host: str = '127.0.0.1'
port: int = 7555
secret_key: str = 'ssswessss'
allow_origins: List[str] = None
settings = Settings(_env_file=os.path.join(BASE_DIR, '.env'))
adminsite.py
from core.settings import settings
from fastapi_user_auth.site import AuthAdminSite
site = AuthAdminSite(settings)
auth = site.auth
from fastapi_scheduler import SchedulerAdmin
scheduler = SchedulerAdmin.bind(site)
界面: