Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

更新文档适配所有示例到最新版 #181

Merged
merged 6 commits into from
Aug 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ everyone's sponsorship and support.
- [SQLModel](https://sqlmodel.tiangolo.com/): Finish `ORM` model mapping. Perfectly
combine [SQLAlchemy](https://www.sqlalchemy.org/) with [Pydantic](https://pydantic-docs.helpmanual.io/), and have all
their features .
- [Amis](https://baidu.gitee.io/amis): Finish admin page presentation.
- [Amis](https://baidu.github.io/amis/): Finish admin page presentation.

## Composition

Expand Down
2 changes: 1 addition & 1 deletion README.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
- [SQLModel](https://sqlmodel.tiangolo.com/) 负责ORM模型映射(
完美结合[SQLAlchemy](https://www.sqlalchemy.org/)+[Pydantic](https://pydantic-docs.helpmanual.io/), 拥有`SQLAlchemy`
和`Pydantic`的所有功能)
- [Amis](https://baidu.gitee.io/amis) 负责Admin后台页面展示
- [Amis](https://aisuda.bce.baidu.com/amis/) 负责Admin后台页面展示

## 项目组成

Expand Down
7 changes: 6 additions & 1 deletion docs/zh/docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ pip install fastapi_amis_admin

```bash
pip install fastapi_amis_admin[sqlmodel]
```
```

## 简单示例

Expand All @@ -110,6 +110,11 @@ if __name__ == '__main__':

uvicorn.run(app)
```
### 运行程序
```bash
uvicorn main:app <--port 端口号> <--reload>
```
--port为指定启动端口(默认8000),--reload为开发过程中允许运行时重载。

## 模型管理示例

Expand Down
3 changes: 2 additions & 1 deletion docs/zh/docs/tutorials/basic/FormAdmin.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ 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):
Expand Down
62 changes: 59 additions & 3 deletions docs/zh/docs/tutorials/basic/Inheritance.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,42 @@ class MyHomeAdmin(admin.HomeAdmin):
# 获取默认页面
page = await super().get_page(request)
# 自定义修改
page.body.title = 'MyHome'
# page.body.title = 'MyHome' # page.body已改为list类型,该行废弃
# 修改后台首页的内页标题
page.title = 'MyHome'
# 后台首页主体尾部追加内容
page.body.append('welcome FastApi-AMIS')
...
return page
```

## 示例-2(自定义模板管理基类)

根目录`templates`文件夹中新建`element.html`,html内容如下:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title }}</title>
</head>
<body>
<h1>{{ title }}</h1>
<p>The current time is: {{ current_time }}</p>
</body>
</html>
```

main.py增加如下代码:
```python linenums="1" hl_lines="6 7 11 20"
import datetime

from fastapi_amis_admin import admin, amis


class MyJinja2Admin(admin.TemplateAdmin):
templates: Jinja2Templates = Jinja2Templates(directory='apps/demo/templates')
templates: Jinja2Templates = Jinja2Templates(directory='templates')


@site.register_admin
Expand All @@ -53,9 +74,44 @@ class ElementTemplateAdmin(MyJinja2Admin):
page_schema = amis.PageSchema(label='ElementUI', icon='fa fa-link')
template_name = 'element.html'

```
async def get_page(self, request: Request) -> Dict[str, Any]:
page = await super().get_page(request)
# 有别于示例1中 admin.HomeAdmin 对page的修改,这里的page来自 admin.TemplateAdmin,是一个dict
page['title'] = 'Element Title' # 该行不会生效
return {'current_time': datetime.datetime.now(), 'title': 'Element Content'}

```
## 示例-3(重用模型管理类)
我们在*模型管理*-示例2的基础上进行改造,将`Article`类新增一行属性`is_active: bool = False # add`,如下:
```python linenums="1" hl_lines="32"
class Article(Base):
__tablename__ = 'article'

id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
title: Mapped[str] = mapped_column(String(200), nullable=False)
description: Mapped[str] = mapped_column(String(400), default='')
status: Mapped[bool] = mapped_column(Boolean, default=False)
content: Mapped[str] = mapped_column(String, nullable=False)
category_id: Mapped[Optional[int]] = mapped_column(Integer, ForeignKey('category.id'))
is_active: bool = False # add

```
然后我们继承原油`ArticleAdmin`重新实现一个新的page类别:
```python
@site.register_admin
class ActiveArticle(ArticleAdmin):
"""继承重用`ArticleAdmin`;此示例较为简单,实际应用可能比较复杂."""
page_schema = PageSchema(label='文章管理(已激活)', icon='fa fa-file')
# 自定义路由前缀
router_prefix = '/article.active'

# 重写基础选择器
async def get_select(self, request: Request) -> Select:
stmt = await super().get_select(request)
return stmt.where(Article.is_active == True)
```
此时,page中将分别有`文章管理`以及`文章管理(已激活)`,后者将只显示`is_active`为True的文章。
## ~~~示例-3(重用模型管理类)~~~

```python linenums="1" hl_lines="32"
from fastapi_amis_admin import admin
Expand Down
66 changes: 40 additions & 26 deletions docs/zh/docs/tutorials/basic/ModelAction.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@
## 自定义工具条动作

### 示例-1

1、增加引用
```python
@site.register_admin
class ArticleAdmin(admin.ModelAdmin):
page_schema = PageSchema(label='文章管理', icon='fa fa-file')
model = Article
from fastapi_amis_admin.admin.admin import AdminAction
from fastapi_amis_admin.amis import ActionType
```
2、修改上一节中`ArticleAdmin`类,`page_schema`改为`page_schema = PageSchema(label='文章管理', icon='fa fa-file')`以增加图标,同时类中增加如下代码,来添加工具条

```python
# 添加自定义工具条动作
admin_action_maker = [
lambda admin: AdminAction(
Expand Down Expand Up @@ -47,13 +48,19 @@ class ArticleAdmin(admin.ModelAdmin):
!!! note annotate "关于`ActionType`"

ActionType事实上是[amis Action 行为按钮](https://baidu.gitee.io/amis/zh-CN/components/action?page=1)组件的一个python模型映射,它支持多种常见的行为类型.例如:ajax请求/下载请求/跳转链接/发送邮件/弹窗/抽屉/复制文本等等.

fastapi_amis_admin的灵活性强体现之一,是因为它是基于amis的组件式开发,你可以在很多地方自由的替换或添加内置的amis组件.在此之前希望你能阅读[amis文档](https://baidu.gitee.io/amis/zh-CN/components/page),对amis核心组件有一定的了解.

## 自定义单项操作动作

我们将在上一步的基础上新增一个自定义普通处理动作
### 示例-2

新增引入
```python
from typing import List
from fastapi_amis_admin.amis import Dialog
```
增加一个普通动作定义:
```python
# 创建普通ajax动作
class TestAction(admin.ModelAction):
Expand All @@ -68,15 +75,31 @@ class TestAction(admin.ModelAction):
...
# 返回动作处理结果
return BaseApiOut(data=dict(item_id=item_id, data=data, items=list(items)))
```
修改`ArticleAdmin`,在`admin_action_maker`的list中追加一行`lambda admin: TestAction(admin, name='test_action', flags=['item', 'bulk'])`变为:


@site.register_admin
class ArticleAdmin(admin.ModelAdmin):
page_schema = PageSchema(label='文章管理', icon='fa fa-file')
model = Article
# 添加自定义单项和批量操作动作
```python
# 添加自定义工具条动作
admin_action_maker = [
lambda admin: TestAction(admin, name='test_action',flags=['item','bulk'])
lambda admin: AdminAction(
admin=admin,
name='test_ajax_action',
action=ActionType.Ajax(
label='工具条ajax动作',
api='https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com/api/amis-mock/mock2/form/saveForm'
),
flags=['toolbar']
),
lambda admin: AdminAction(
admin=admin,
name='test_link_action',
action=ActionType.Link(
label='工具条link动作',
link='https://github.com/amisadmin/fastapi_amis_admin'
),
flags=['toolbar']
),
lambda admin: TestAction(admin, name='test_action', flags=['item', 'bulk'])
]
```

Expand All @@ -90,6 +113,7 @@ class ArticleAdmin(admin.ModelAdmin):

## 自定义批量操作动作

本部分修改方式同上一步。
### 示例-3

```python
Expand All @@ -116,19 +140,9 @@ class TestFormAction(admin.ModelAction):
...
# 返回动作处理结果
return BaseApiOut(data=dict(item_id=item_id, data=data, items=list(items)))


@site.register_admin
class ArticleAdmin(admin.ModelAdmin):
page_schema = PageSchema(label='文章管理', icon='fa fa-file')
model = Article

# 添加自定义单项和批量操作动作
admin_action_maker = [
lambda admin: TestAction(admin, name='test_action',flags=['item','bulk'])
]

```
在`admin_action_maker`的list中追加一行`lambda admin: TestFormAction(admin, name='test_form_action', flags=['item', 'bulk'])`


示例-3与示例-2非常相似, 但是它允许用户添加一个自定义表单,这个在很多情况下,非常有用.

Expand Down
79 changes: 75 additions & 4 deletions docs/zh/docs/tutorials/basic/ModelAdmin.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,48 @@
模型管理在后台管理中是最为常用的一个管理类,其使用功能也是最为丰富的. fastapi-amis-admin目前已经实现针对数据模型常用的各种基本操作,
并且你仍然可以在此基础上做出更多个性化的拓展.

## 示例-1
## 示例1(基于SQLAlchemy 2.0)
```python
from sqlalchemy import String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from typing import Optional


class Base(DeclarativeBase):
pass


class CategorySchema(BaseModel):
id: Optional[int] = Field(default=None, primary_key=True, nullable=False)
name: str = Field(title="CategoryName")
description: str = Field(default="", title="CategoryDescription")

class Config:
# orm_mode = True
from_attributes = True


# 创建SQLAlchemy 2.0模型,详细请参考: https://docs.sqlalchemy.org/en/20/orm/quickstart.html
class Category(Base):
__tablename__ = "category"
__pydantic_model__ = CategorySchema # 指定模型对应的Schema类.省略可自动生成,但是建议指定.

id: Mapped[int] = mapped_column(primary_key=True, nullable=False)
name: Mapped[str] = mapped_column(String(100), unique=True, index=True, nullable=False)
description: Mapped[str] = mapped_column(String(255), default="")
```
在`app = FastAPI()`下方添加以下内容来创建数据表:
```python
@app.on_event("startup")
async def startup():
await site.db.async_run_sync(Category.metadata.create_all, is_session=False)
pass
```

## ~~示例-1(基于SQLModel)~~

```python

# 先创建一个SQLModel模型,详细请参考: https://sqlmodel.tiangolo.com/
class Category(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True, nullable=False)
Expand All @@ -30,10 +69,42 @@ class CategoryAdmin(admin.ModelAdmin):
!!! note annotate "关于SQLModel模型"

事实上这部分代码并不属于`amis-admin`的代码,因为它可以用重用在任何需要ORM映射的地方, 在项目中你应该单独定义一个`models.py`文件编写这部分代码.

SQLModel是一个非常优秀的Python ORM库,由FastAPI同一位作者编写,完美的结合了SQLAlchemy和Pydantic.请阅读它的官方文档: https://sqlmodel.tiangolo.com/

## 示例-2
## 示例-2(基于SQLAlchemy 2.0)
```python
from sqlalchemy import String, Integer, Boolean, ForeignKey, Select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from typing import Optional

class Article(Base):
__tablename__ = 'article'

id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
title: Mapped[str] = mapped_column(String(200), nullable=False)
description: Mapped[str] = mapped_column(String(400), default='')
status: Mapped[bool] = mapped_column(Boolean, default=False)
content: Mapped[str] = mapped_column(String, nullable=False)
category_id: Mapped[Optional[int]] = mapped_column(Integer, ForeignKey('category.id'))


@site.register_admin
class ArticleAdmin(admin.ModelAdmin):
page_schema = '文章管理'
model = Article
# 设置需要展示的字段
list_display = [Article.id, Article.title, Article.description, Article.status, Category.name]
# 设置模糊搜索字段
search_fields = [Article.title, Category.name]

# 自定义基础选择器
async def get_select(self, request: Request) -> Select:
stmt = await super().get_select(request)
return stmt.outerjoin(Category, Article.category_id == Category.id)
```
同时,将前文定义的`def startup()`函数追加一行`await site.db.async_run_sync(Article.metadata.create_all, is_session=False)`用于生成对应数据表。
## ~~~示例-2(基于SQLModel)~~~

```python
# 创建一个SQLModel模型,详细请参考: https://sqlmodel.tiangolo.com/
Expand Down Expand Up @@ -140,6 +211,6 @@ class ArticleAdmin(admin.ModelAdmin):
!!! note annotate "关于fastapi_amis_admin与django-admin"

[django-admin](https://docs.djangoproject.com/zh-hans/4.0/ref/contrib/admin/)是一个非常成熟强大的web管理后台工具,使用django的用户应该经常使用到它,但他是并不适用于非django项目,这也是fastapi_amis_admin诞生的主要原因之一.

fastapi_amis_admin相比django-admin拥有更多的拓展与功能,但是fastapi_amis_admin目前仍然处于成长阶段,很多功能并不成熟,需要漫长的不断完善与升级.非常期待你参与到[fastapi_amis_admin](https://github.com/amisadmin/fastapi_amis_admin)的项目开发之中,为项目贡献代码,或为项目[提供建议](https://github.com/amisadmin/fastapi_amis_admin/issues).

14 changes: 11 additions & 3 deletions docs/zh/docs/tutorials/basic/PageAdmin.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,14 @@
## 页面管理

`PageAdmin`实现在菜单列表显示一个菜单.点击菜单后将展现一个`amis`页面.
你可以通过阅读[`baidu-amis`官方文档](https://baidu.gitee.io/amis/zh-CN/components/page)
你可以通过阅读[`baidu-amis`官方文档(国内)](https://aisuda.bce.baidu.com/amis/zh-CN/components/page)
,实现各种复杂的页面展示.先看一个Hello World页面示例吧.

在main.py中的`site.mount_app(app)`上方添加:
```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'
Expand All @@ -21,7 +25,11 @@ class HelloWorldPageAdmin(admin.PageAdmin):

非常简单吧,接下来再实现一个获取当前时间的页面.

在main.py中的`site.mount_app(app)`上方添加:
```python
import time
from fastapi import Request

@site.register_admin
class CurrentTimePageAdmin(admin.PageAdmin):
page_schema = 'Current Time Page'
Expand All @@ -43,7 +51,7 @@ class CurrentTimePageAdmin(admin.PageAdmin):
@site.register_admin
class AmisPageAdmin(admin.PageAdmin):
page_schema = 'Amis Json Page'
page = Page.parse_obj(
page = Page.model_validate(
{
"type": "page",
"title": "表单页面",
Expand All @@ -67,7 +75,7 @@ class AmisPageAdmin(admin.PageAdmin):
}
)
```

!!! note annotate 注意,所有装饰器`@site.register_admin`涉及的类都应在`site.mount_app(app)`之前注册。
## 链接管理

`LinkAdmin`实现在菜单列表显示一个链接跳转菜单.点击菜单后将通过打开一个新的浏览器标签,访问设置的链接:
Expand Down
Loading