maui 开发音乐播放APP 优化 用fastapi_amis_admin创建后台及接口(5)

2023-12-14 22:54:41

相关的models

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="歌曲URL", max_length=200)
    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))

再准备一下菜单页面代码:

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.label("操作者"),
        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

接口:

from apps.music.models import Article, ArticleStatus,Category
from core.adminsite import auth, site
from fastapi import APIRouter, Depends
from sqlalchemy import delete, insert, select, update,join,func, not_

from sqlmodel.ext.asyncio.session import AsyncSession
from fastapi import Depends, Query
# 通过注册依赖方式验证用户权限,当前路由注册器下全部路由都将进行权限验证.
# router = APIRouter(prefix="/musics", tags=["ArticleAPI"], dependencies=[Depends(auth.requires()())])

router = APIRouter(prefix="/api")


@router.get("/listmusic", summary="读取歌曲表")
@router.get("/listmusic/{name}", summary="读取歌曲表")
async def list_articles(
    name: str = '',
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, le=100, description="每页数量"),
    db: AsyncSession = Depends(site.db.session_generator)
):
    # 构建基本查询
    query = select([
        Article.id,
        Article.title,
        Article.img,
        Article.url,
        Article.content,
        Article.source,
        Category.name.label("category_name")
    ]).select_from(
        join(Article,Category, Category.id == Article.category_id)
    )

    # 添加模糊查询条件
    if name:
        query = query.where(func.lower(Article.title).like(func.lower(f"%{name}%")))

    # 计算偏移量
    offset = (page - 1) * page_size

    # 添加分页条件
    query = query.offset(offset).limit(page_size)

    # 执行查询
    result = await db.execute(query)

    # 获取查询结果
    articles = result.fetchall()

    return articles
@router.get("/{id}", response_model=Article, summary="读取歌曲详情")
async def read_article(id: int, session: AsyncSession = Depends(site.db.session_generator)):
    return await session.get(Article, id)

以下是接口请求结果:
在这里插入图片描述
代码下载

文章来源:https://blog.csdn.net/hzether/article/details/135004028
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。