Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc1e9afe0c | ||
|
|
6220f979bf | ||
|
|
6ec05fd3f9 | ||
|
|
8c3e43b85b | ||
|
|
248145b821 | ||
|
|
261a983678 | ||
|
|
1a7e457054 | ||
|
|
7ae59415e8 | ||
|
|
c50d5e7921 | ||
|
|
af873bf45e | ||
|
|
4384a3000c | ||
|
|
72a951a2b6 | ||
|
|
38a5136e69 | ||
|
|
96dbeb0cbd | ||
|
|
936c37c65c | ||
|
|
e51c86c83f | ||
|
|
71a25f4774 | ||
|
|
56563657e8 | ||
|
|
6bfb10e4a4 | ||
|
|
70cb8eb35b | ||
|
|
cdea48c7d4 | ||
|
|
fba22bbcbf | ||
|
|
14f96abdb3 | ||
|
|
28ff95bf0d | ||
|
|
6cee5a6104 | ||
|
|
3add95e910 | ||
|
|
1db1064c11 | ||
|
|
f75928119e | ||
|
|
9051e8138c | ||
|
|
8396f49105 | ||
|
|
c664c70bbc | ||
|
|
7a503cd94a | ||
|
|
7a9aeec8db | ||
|
|
2c57bc36ea | ||
|
|
c0fc70425b | ||
|
|
f95944a781 | ||
|
|
589e0c8ce7 | ||
|
|
6e0ff64893 | ||
|
|
044e432eb7 | ||
|
|
5887079ade | ||
|
|
724e0817a5 | ||
|
|
9caa7a22e5 | ||
|
|
c2042d5f80 | ||
|
|
51f17c9539 | ||
|
|
27ed99ee27 | ||
|
|
7eb41e9754 | ||
|
|
c7f266a482 | ||
|
|
f2d444b877 | ||
|
|
9e59035300 | ||
|
|
b0ed2100a2 | ||
|
|
6f0c86fba6 | ||
|
|
c71562a12f | ||
|
|
a7fa415545 | ||
|
|
24d2523385 | ||
|
|
d30a3d79de | ||
|
|
860d5778cc | ||
|
|
23dbe9ee9c | ||
|
|
9114964ef2 | ||
|
|
56615528b9 | ||
|
|
1b5c54daf9 | ||
|
|
c0a3f5243b | ||
|
|
d22eb22f74 | ||
|
|
7eeb4c2489 | ||
|
|
d691c444ae | ||
|
|
83c23ea276 | ||
|
|
cff67d152f | ||
|
|
ad67c289d3 | ||
|
|
4a4d8f763d | ||
|
|
dfc734c13a | ||
|
|
654f441d05 | ||
|
|
48eebc1c95 | ||
|
|
3c1764e58d | ||
|
|
233241c962 | ||
|
|
30f9774ab1 | ||
|
|
a255c746d4 | ||
|
|
eac2a1c941 | ||
|
|
110a5faaff | ||
|
|
f3cfdcf580 | ||
|
|
34a1066cd0 | ||
|
|
67d05c39f3 | ||
|
|
fa49130c4f | ||
|
|
5b76973d9c | ||
|
|
0d57a2a8f2 | ||
|
|
78b7dae880 | ||
|
|
04a89144ba | ||
|
|
3b3eecc1d1 | ||
|
|
ca92d949dd | ||
|
|
663c7925e3 | ||
|
|
76b2ad6f58 | ||
|
|
fd8dcfee40 | ||
|
|
0a60c1960d | ||
|
|
28021df2ab | ||
|
|
6d42b6d56c | ||
|
|
3b467f42fe | ||
|
|
e37749c669 | ||
|
|
2cbbf25060 | ||
|
|
986ae4e4bc | ||
|
|
103aaf4911 | ||
|
|
7038ce64a6 | ||
|
|
9b8525ca1e | ||
|
|
254ce53387 | ||
|
|
0ff0c456b0 | ||
|
|
57a54090bb | ||
|
|
e3d3424ee1 | ||
|
|
99b2f611ec | ||
|
|
a675d78b82 | ||
|
|
62bd10cc60 | ||
|
|
14a32e6d3c | ||
|
|
5e08f3e49b |
@@ -1,3 +1,29 @@
|
|||||||
|
# flask配置
|
||||||
|
FLASK_APP=app.py
|
||||||
FLASK_ENV=development
|
FLASK_ENV=development
|
||||||
FLASK_RUN_HOST=0.0.0.0
|
FLASK_DEBUG=1
|
||||||
FLASK_APP='applications:create_app'
|
FLASK_RUN_HOST = 127.0.0.1
|
||||||
|
FLASK_RUN_PORT = 5000
|
||||||
|
|
||||||
|
# pear admin flask配置
|
||||||
|
SYSTEM_NAME = Pear Admin
|
||||||
|
|
||||||
|
# MySql配置信息
|
||||||
|
MYSQL_HOST=127.0.0.1
|
||||||
|
# MYSQL_HOST=dbserver
|
||||||
|
MYSQL_PORT=3306
|
||||||
|
MYSQL_DATABASE=PearAdminFlask
|
||||||
|
MYSQL_USERNAME=root
|
||||||
|
MYSQL_PASSWORD=123456
|
||||||
|
|
||||||
|
# Redis 配置
|
||||||
|
# REDIS_HOST=127.0.0.1
|
||||||
|
# REDIS_PORT=6379
|
||||||
|
|
||||||
|
# 密钥配置(记得改)
|
||||||
|
SECRET_KEY='pear-admin-flask'
|
||||||
|
|
||||||
|
# 邮箱配置
|
||||||
|
MAIL_SERVER='smtp.qq.com'
|
||||||
|
MAIL_USERNAME='123@qq.com'
|
||||||
|
MAIL_PASSWORD='XXXXX' # 生成的授权码
|
||||||
@@ -116,9 +116,3 @@ dmypy.json
|
|||||||
|
|
||||||
#ide
|
#ide
|
||||||
.idea/
|
.idea/
|
||||||
|
|
||||||
# 数据库文件
|
|
||||||
*.db
|
|
||||||
#上传到本地的图片文件
|
|
||||||
*upload/
|
|
||||||
migrations/
|
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
FROM python:3.7-alpine
|
||||||
|
|
||||||
|
|
||||||
|
RUN apk update \
|
||||||
|
&& apk --update add --no-cache gcc \
|
||||||
|
&& apk --update add --no-cache g++ \
|
||||||
|
&& apk --update add --no-cache tzdata \
|
||||||
|
&& apk --update add --no-cache libffi-dev \
|
||||||
|
&& apk --update add --no-cache libxslt-dev \
|
||||||
|
&& apk --update add --no-cache jpeg-dev
|
||||||
|
|
||||||
|
ENV TIME_ZONE Asia/Shanghai
|
||||||
|
ENV PIPURL "https://pypi.tuna.tsinghua.edu.cn/simple"
|
||||||
|
|
||||||
|
RUN echo "${TIME_ZONE}" > /etc/timezone \
|
||||||
|
&& ln -sf /usr/share/zoneinfo/${TIME_ZONE} /etc/localtime
|
||||||
|
|
||||||
|
COPY . /app
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN pip --no-cache-dir install -i ${PIPURL} --upgrade pip \
|
||||||
|
&& pip --no-cache-dir install -i ${PIPURL} -r requirement/requirement-dev.txt \
|
||||||
|
&& pip --no-cache-dir install -i ${PIPURL} gunicorn \
|
||||||
|
&& chmod +x start.sh
|
||||||
|
CMD ./start.sh
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
<br/>
|
<br/>
|
||||||
<br/>
|
<br/>
|
||||||
<img src="https://gitee.com/pear-admin/Pear-Admin-Layui/raw/master/admin/images/logo.png" width="90px" style="margin-top:30px;"/>
|
|
||||||
<h1 align="center">
|
<h1 align="center">
|
||||||
Pear Admin Flask
|
Pear Admin Flask
|
||||||
</h1>
|
</h1>
|
||||||
@@ -9,7 +8,7 @@
|
|||||||
开 箱 即 用 的 Flask 快 速 开 发 平 台
|
开 箱 即 用 的 Flask 快 速 开 发 平 台
|
||||||
</h4>
|
</h4>
|
||||||
|
|
||||||
[预 览](http://flask.pearadmin.com) | [官 网](http://www.pearadmin.com/) | [群聊](https://jq.qq.com/?_wv=1027&k=5OdSmve) | [社区](http://forum.pearadmin.com/)
|
[预 览](http://flask.pearadmin.com) | [官 网](http://www.pearadmin.com/) | [群聊](https://jq.qq.com/?_wv=1027&k=TkLAKUxC) | [社区](http://forum.pearadmin.com/)
|
||||||
|
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
@@ -29,112 +28,137 @@
|
|||||||
<img width="92%" style="border-radius:10px;margin-top:20px;margin-bottom:20px;box-shadow: 2px 0 6px gray;" src="https://images.gitee.com/uploads/images/2020/1019/104805_042b888c_4835367.png" />
|
<img width="92%" style="border-radius:10px;margin-top:20px;margin-bottom:20px;box-shadow: 2px 0 6px gray;" src="https://images.gitee.com/uploads/images/2020/1019/104805_042b888c_4835367.png" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
## 项目简介
|
#### 项目简介
|
||||||
Pear Admin Flask 基于 Flask 生态的后台管理系统,该项目旨在为 python 开发者提供一个快速开发前后端半分离的后台管理系统的模板
|
>Pear Admin Flask 基于 Flask 的后台管理系统,拥抱应用广泛的python语言,通过使用本系统,即可快速构建你的功能业务
|
||||||
|
>
|
||||||
|
>项目旨在为python开发者提供一个后台管理系统的模板,成为您构建信息管理系统,物联网后台....等等应用时灵活,简单的工具
|
||||||
|
>
|
||||||
|
>众人拾柴火焰高,欢迎pythoner参与项目~
|
||||||
|
|
||||||
在使用本项目之前最好掌握以下知识点
|
|
||||||
|
|
||||||
+ [html、css、JavaScript](https://developer.mozilla.org/zh-CN/docs/Learn/HTML)
|
|
||||||
+ [jQuery](https://www.w3school.com.cn/jquery/index.asp)
|
|
||||||
+ [layui](https://www.layui.com/)
|
|
||||||
+ [flask](https://dormousehole.readthedocs.io/en/latest/)
|
|
||||||
+ [flask-login](https://flask-login.readthedocs.io/en/latest/)
|
|
||||||
+ [flask-sqlalchemy](http://www.pythondoc.com/flask-sqlalchemy/quickstart.html)
|
|
||||||
+ [flask-restful](https://flask-restful.readthedocs.io/en/latest/)
|
|
||||||
|
|
||||||
|
|
||||||
## 预览
|
|
||||||
Pear Admin Flask 有以下几个版本:
|
Pear Admin Flask 有以下几个版本:
|
||||||
|
|
||||||
[master分支版本 ](https://gitee.com/pear-admin/pear-admin-flask/tree/master/)
|
[master分支版本 ](https://gitee.com/pear-admin/pear-admin-flask/tree/master/)
|
||||||
|
|
||||||
>flask 2.x + flask-sqlalchemy + 权限验证 + Flask-APScheduler 定时任务 + marshmallow 序列化与数据验证
|
> flask 2.0.1 + flask-sqlalchemy + mysql + 权限验证 + Flask-APScheduler 定时任务 + marshmallow 序列化与数据验证
|
||||||
|
|
||||||
[Mini 分支版本 ](https://gitee.com/pear-admin/pear-admin-flask/tree/mini/)
|
[Mini 分支版本 ](https://gitee.com/pear-admin/pear-admin-flask/tree/mini/)
|
||||||
|
|
||||||
>flask 2.x + flask-sqlalchemy + Flask-restful + 基于角色的权限管理
|
>flask 2.0.1 + flask-sqlalchemy + sqllite + 权限验证 + Flask-RESTful 序列化与数据验证
|
||||||
|
|
||||||
| | |
|
[v1 分支版本(不再更新,仅供参考) ](https://gitee.com/pear-admin/pear-admin-flask/tree/v1/)
|
||||||
|---------------------|---------------------|
|
|
||||||
|  |  |
|
|
||||||
| |  |
|
|
||||||
|  |  |
|
|
||||||
|
|
||||||
## 内置功能
|
>flask 1.12 + flask-sqlalchemy + mysql + 权限验证 + marshmallow 序列化与数据验证
|
||||||
|
|
||||||
|
[simple 分支版本(不再更新,仅供参考) ](https://gitee.com/pear-admin/pear-admin-flask/tree/simple/)
|
||||||
|
|
||||||
|
>flask 1.12 + flask-sqlalchemy + mysql + 极简权限 + marshmallow 序列化与数据验证
|
||||||
|
>
|
||||||
|
>项目最简版本
|
||||||
|
|
||||||
|
#### 内置功能
|
||||||
|
|
||||||
- [x] 用户管理:用户是系统操作者,该功能主要完成系统用户配置。
|
- [x] 用户管理:用户是系统操作者,该功能主要完成系统用户配置。
|
||||||
- [x] 权限管理:配置系统菜单,操作权限,按钮权限标识等。
|
- [x] 权限管理:配置系统菜单,操作权限,按钮权限标识等。
|
||||||
- [x] 角色管理:角色菜单权限分配。
|
- [x] 角色管理:角色菜单权限分配。
|
||||||
- [x] 操作日志:系统正常操作日志记录和查询;系统异常信息日志记录和查询。
|
- [x] 操作日志:系统正常操作日志记录和查询;系统异常信息日志记录和查询。
|
||||||
- [x] 登录日志:系统登录日志记录查询包含登录异常。
|
- [x] 登录日志:系统登录日志记录查询包含登录异常。
|
||||||
|
- [x] 服务监控:监视当前系统CPU、内存、磁盘、python版本,运行时长等相关信息。
|
||||||
- [x] 文件上传: 图片上传示例
|
- [x] 文件上传: 图片上传示例
|
||||||
|
- [x] 定时任务: 简单的定时任务
|
||||||
|
- [ ] 代码生成: 构想中....
|
||||||
|
|
||||||
|
#### 项目结构
|
||||||
|
|
||||||
## 文档
|
```
|
||||||
正在编写
|
Pear Admin Flask
|
||||||
|
├─applications # 应用
|
||||||
|
│ ├─configs # 配置文件
|
||||||
|
│ │ ├─ common.py # 普通配置
|
||||||
|
│ │ └─ config.py # 配置文件对象
|
||||||
|
│ ├─extensions # 注册插件
|
||||||
|
│ ├─models # 数据模型
|
||||||
|
│ ├─static # 静态资源文件
|
||||||
|
│ ├─templates # 静态模板文件
|
||||||
|
│ └─views # 视图部分
|
||||||
|
│ ├─admin # 后台管理视图模块
|
||||||
|
│ └─index # 前台视图模块
|
||||||
|
├─docs # 文档说明(占坑)
|
||||||
|
├─migrations # 迁移文件记录
|
||||||
|
├─requirement # 依赖文件
|
||||||
|
├─test # 测试文件夹(占坑)
|
||||||
|
└─.env # 项目的配置文件
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
## 安装使用
|
#### 项目安装
|
||||||
|
|
||||||
+ 下载源码
|
|
||||||
```bash
|
```bash
|
||||||
|
# 下 载
|
||||||
git clone https://gitee.com/pear-admin/pear-admin-flask
|
git clone https://gitee.com/pear-admin/pear-admin-flask
|
||||||
|
|
||||||
# 进入 pear-admin-flask 代码根目录
|
# 安 装
|
||||||
cd pear-admin-flask
|
pip install -r requirement\requirement-dev.txt
|
||||||
|
|
||||||
|
# 配 置
|
||||||
|
.env
|
||||||
|
|
||||||
# 切换分支
|
|
||||||
git checkout mini
|
|
||||||
```
|
```
|
||||||
|
|
||||||
+ 安装依赖
|
#### 修改配置
|
||||||
|
|
||||||
|
```python
|
||||||
|
.env
|
||||||
|
# MySql配置信息
|
||||||
|
MYSQL_HOST=127.0.0.1
|
||||||
|
MYSQL_PORT=3306
|
||||||
|
MYSQL_DATABASE=PearAdminFlask
|
||||||
|
MYSQL_USERNAME=root
|
||||||
|
MYSQL_PASSWORD=root
|
||||||
|
|
||||||
|
# Redis 配置
|
||||||
|
REDIS_HOST=127.0.0.1
|
||||||
|
REDIS_PORT=6379
|
||||||
|
|
||||||
|
# 密钥配置
|
||||||
|
SECRET_KEY='pear-admin-flask'
|
||||||
|
|
||||||
|
# 邮箱配置
|
||||||
|
MAIL_SERVER='smtp.qq.com'
|
||||||
|
MAIL_USERNAME='123@qq.com'
|
||||||
|
MAIL_PASSWORD='XXXXX' # 生成的授权码
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Venv 安装
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 创建虚拟环境
|
|
||||||
python -m venv venv
|
python -m venv venv
|
||||||
|
|
||||||
# 然后使虚拟环境生效(windows)
|
|
||||||
venv\Scripts\activate
|
|
||||||
# source venv/bin/activate # (Linux激活虚拟环境)
|
|
||||||
|
|
||||||
# 安装依赖
|
|
||||||
pip install -r requirement.txt
|
|
||||||
```
|
```
|
||||||
|
|
||||||
+ 数据迁移
|
#### 运行项目
|
||||||
|
|
||||||
默认的使用 `sqlite3` 作为测试环境的数据库进行演示,不需要按照mysql即可查看演示。如果需要二次开发,建议改成 `mysql` 。
|
|
||||||
|
|
||||||
如果需要在开发环境使用 mysql 作为数据库,请查看 `applications/configs/config.py` 文件里面的相关配置文件, 注释掉 sqlite 的配置即可
|
|
||||||
|
|
||||||
如果需要修改数据的配置信息,请在 `.flaskenv` 里面调整即可
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
flask db init
|
# 初 始 化 数 据 库
|
||||||
flask db migrate -m '数据初始化'
|
|
||||||
flask db upgrade
|
|
||||||
|
|
||||||
flask init-db
|
flask init
|
||||||
```
|
```
|
||||||
|
|
||||||
+ 项目启动
|
执行 flask run 命令启动项目
|
||||||
|
|
||||||
|
#### 命令行创建视图
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
flask run
|
# 示例
|
||||||
|
|
||||||
|
flask new --type view --name test/a
|
||||||
|
|
||||||
|
# 自动注册蓝图
|
||||||
|
# 访问http://127.0.0.1:5000/test/a/
|
||||||
```
|
```
|
||||||
|
|
||||||
## Git 贡献提交规范
|
#### 预览项目
|
||||||
|
|
||||||
- 参考 [vue](https://github.com/vuejs/vue/blob/dev/.github/COMMIT_CONVENTION.md) 规范 ([Angular](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular))
|
| | |
|
||||||
- `feat` 增加新功能
|
|---------------------|---------------------|
|
||||||
- `fix` 修复问题/BUG
|
|  |  |
|
||||||
- `style` 代码风格相关无影响运行结果的
|
| |  |
|
||||||
- `perf` 优化/性能提升
|
|  |  |
|
||||||
- `refactor` 重构
|
|
||||||
- `revert` 撤销修改
|
|
||||||
- `test` 测试相关
|
|
||||||
- `docs` 文档/注释
|
|
||||||
- `chore` 依赖更新/脚手架配置修改等
|
|
||||||
- `workflow` 工作流改进
|
|
||||||
- `ci` 持续集成
|
|
||||||
- `types` 类型定义文件更改
|
|
||||||
- `wip` 开发中
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
from applications import create_app
|
||||||
|
from flask_migrate import Migrate
|
||||||
|
from applications.extensions import db
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
|
||||||
|
migrate = Migrate(app, db)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
app.run()
|
||||||
+12
-28
@@ -1,34 +1,21 @@
|
|||||||
import os
|
import os
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
from flask import Flask, Blueprint
|
from applications.common.script import init_script
|
||||||
|
from applications.extensions import init_plugs
|
||||||
import config
|
|
||||||
from applications.view import init_view
|
from applications.view import init_view
|
||||||
from common import register_api
|
from applications.configs import config
|
||||||
from common.flask_uploads import configure_uploads
|
|
||||||
from common.utils.upload import photos
|
|
||||||
from extensions import init_plugs
|
|
||||||
|
|
||||||
api_bp: Blueprint = Blueprint('api', __name__, url_prefix='/api/v1')
|
|
||||||
|
|
||||||
from .rights import register_rights_api
|
|
||||||
from .system import register_sys_api
|
|
||||||
from .users import register_users_api
|
|
||||||
|
|
||||||
register_rights_api(api_bp)
|
|
||||||
register_users_api(api_bp)
|
|
||||||
register_sys_api(api_bp)
|
|
||||||
|
|
||||||
|
|
||||||
def init_api(app: Flask) -> None:
|
def create_app(config_name=None):
|
||||||
app.register_blueprint(api_bp)
|
app = Flask(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
||||||
|
|
||||||
|
if not config_name:
|
||||||
def create_app() -> Flask:
|
# 尝试从本地环境中读取
|
||||||
app = Flask('pear-admin-flask')
|
config_name = os.getenv('FLASK_CONFIG', 'development')
|
||||||
|
|
||||||
# 引入数据库配置
|
# 引入数据库配置
|
||||||
app.config.from_object(config)
|
app.config.from_object(config[config_name])
|
||||||
|
|
||||||
# 注册各种插件
|
# 注册各种插件
|
||||||
init_plugs(app)
|
init_plugs(app)
|
||||||
@@ -36,11 +23,8 @@ def create_app() -> Flask:
|
|||||||
# 注册路由
|
# 注册路由
|
||||||
init_view(app)
|
init_view(app)
|
||||||
|
|
||||||
# 注册接口(restful api)
|
# 注册命令
|
||||||
init_api(app)
|
init_script(app)
|
||||||
|
|
||||||
# 文件上传
|
|
||||||
configure_uploads(app, photos)
|
|
||||||
|
|
||||||
if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
|
if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
|
||||||
logo()
|
logo()
|
||||||
|
|||||||
@@ -0,0 +1,145 @@
|
|||||||
|
import copy
|
||||||
|
from collections import OrderedDict
|
||||||
|
from io import BytesIO
|
||||||
|
from flask import session, make_response, current_app
|
||||||
|
from flask_login import current_user
|
||||||
|
|
||||||
|
from applications.common.utils.gen_captcha import gen_captcha
|
||||||
|
from applications.schemas import PowerOutSchema
|
||||||
|
|
||||||
|
|
||||||
|
# 授权路由存入session
|
||||||
|
def add_auth_session():
|
||||||
|
role = current_user.role
|
||||||
|
user_power = []
|
||||||
|
for i in role:
|
||||||
|
if i.enable == 0:
|
||||||
|
continue
|
||||||
|
for p in i.power:
|
||||||
|
if p.enable == 0:
|
||||||
|
continue
|
||||||
|
user_power.append(p.code)
|
||||||
|
session['permissions'] = user_power
|
||||||
|
|
||||||
|
|
||||||
|
# 生成菜单树
|
||||||
|
def make_menu_tree():
|
||||||
|
role = current_user.role
|
||||||
|
powers = []
|
||||||
|
for i in role:
|
||||||
|
# 如果角色没有被启用就直接跳过
|
||||||
|
if i.enable == 0:
|
||||||
|
continue
|
||||||
|
# 变量角色用户的权限
|
||||||
|
for p in i.power:
|
||||||
|
# 如果权限关闭了就直接跳过
|
||||||
|
if p.enable == 0:
|
||||||
|
continue
|
||||||
|
# 一二级菜单
|
||||||
|
if int(p.type) in [0,1] and p not in powers:
|
||||||
|
powers.append(p)
|
||||||
|
|
||||||
|
power_schema = PowerOutSchema(many=True) # 用已继承 ma.ModelSchema 类的自定制类生成序列化类
|
||||||
|
power_dict = power_schema.dump(powers) # 生成可序列化对象
|
||||||
|
power_dict.sort(key=lambda x: (x['parent_id'], x['id']), reverse=True)
|
||||||
|
|
||||||
|
menu_dict = OrderedDict()
|
||||||
|
for _dict in power_dict:
|
||||||
|
if _dict['id'] in menu_dict:
|
||||||
|
# 当前节点添加子节点
|
||||||
|
_dict['children'] = copy.deepcopy(menu_dict[_dict['id']])
|
||||||
|
_dict['children'].sort(key=lambda item: item['sort'])
|
||||||
|
# 删除子节点
|
||||||
|
del menu_dict[_dict['id']]
|
||||||
|
|
||||||
|
if _dict['parent_id'] not in menu_dict:
|
||||||
|
menu_dict[_dict['parent_id']] = [_dict]
|
||||||
|
else:
|
||||||
|
menu_dict[_dict['parent_id']].append(_dict)
|
||||||
|
return sorted(menu_dict.get(0), key=lambda item: item['sort'])
|
||||||
|
|
||||||
|
|
||||||
|
# 生成验证码
|
||||||
|
def get_captcha():
|
||||||
|
code, image = gen_captcha()
|
||||||
|
out = BytesIO()
|
||||||
|
session["code"] = code
|
||||||
|
image.save(out, 'png')
|
||||||
|
out.seek(0)
|
||||||
|
resp = make_response(out.read())
|
||||||
|
resp.content_type = 'image/png'
|
||||||
|
return resp, code
|
||||||
|
|
||||||
|
|
||||||
|
def get_render_config():
|
||||||
|
# 网站配置
|
||||||
|
config = dict(logo={
|
||||||
|
# 网站名称
|
||||||
|
"title": current_app.config.get("SYSTEM_NAME"),
|
||||||
|
# 网站图标
|
||||||
|
"image": "/static/admin/admin/images/logo.png"
|
||||||
|
# 菜单配置
|
||||||
|
}, menu={
|
||||||
|
# 菜单数据来源
|
||||||
|
"data": "/rights/menu",
|
||||||
|
"collaspe": False,
|
||||||
|
# 是否同时只打开一个菜单目录
|
||||||
|
"accordion": True,
|
||||||
|
"method": "GET",
|
||||||
|
# 是否开启多系统菜单模式
|
||||||
|
"control": False,
|
||||||
|
# 顶部菜单宽度 PX
|
||||||
|
"controlWidth": 500,
|
||||||
|
# 默认选中的菜单项
|
||||||
|
"select": "0",
|
||||||
|
# 是否开启异步菜单,false 时 data 属性设置为菜单数据,false 时为 json 文件或后端接口
|
||||||
|
"async": True
|
||||||
|
}, tab={
|
||||||
|
# 是否开启多选项卡
|
||||||
|
"enable": True,
|
||||||
|
# 切换选项卡时,是否刷新页面状态
|
||||||
|
"keepState": True,
|
||||||
|
# 是否开启 Tab 记忆
|
||||||
|
"session": True,
|
||||||
|
# 最大可打开的选项卡数量
|
||||||
|
"max": 30,
|
||||||
|
"index": {
|
||||||
|
# 标识 ID , 建议与菜单项中的 ID 一致
|
||||||
|
"id": "10",
|
||||||
|
# 页面地址
|
||||||
|
"href": "/admin/welcome",
|
||||||
|
# 标题
|
||||||
|
"title": "首页"
|
||||||
|
}
|
||||||
|
}, theme={
|
||||||
|
# 默认主题色,对应 colors 配置中的 ID 标识
|
||||||
|
"defaultColor": "2",
|
||||||
|
# 默认的菜单主题 dark-theme 黑 / light-theme 白
|
||||||
|
"defaultMenu": "dark-theme",
|
||||||
|
# 是否允许用户切换主题,false 时关闭自定义主题面板
|
||||||
|
"allowCustom": True
|
||||||
|
}, colors=[{
|
||||||
|
"id": "1",
|
||||||
|
"color": "#2d8cf0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "2",
|
||||||
|
"color": "#5FB878"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "3",
|
||||||
|
"color": "#1E9FFF"
|
||||||
|
}, {
|
||||||
|
"id": "4",
|
||||||
|
"color": "#FFB800"
|
||||||
|
}, {
|
||||||
|
"id": "5",
|
||||||
|
"color": "darkgray"
|
||||||
|
}
|
||||||
|
], links=current_app.config.get("SYSTEM_PANEL_LINKS"), other={
|
||||||
|
# 主页动画时长
|
||||||
|
"keepLoad": 1200,
|
||||||
|
# 布局顶部主题
|
||||||
|
"autoHead": False
|
||||||
|
}, header=False)
|
||||||
|
return config
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
from flask_login import current_user
|
||||||
|
|
||||||
|
from applications.common.utils.validate import xss_escape
|
||||||
|
from applications.extensions import db
|
||||||
|
from applications.models import AdminLog
|
||||||
|
|
||||||
|
|
||||||
|
def login_log(request, uid, is_access):
|
||||||
|
info = {
|
||||||
|
'method': request.method,
|
||||||
|
'url': request.path,
|
||||||
|
'ip': request.remote_addr,
|
||||||
|
'user_agent': xss_escape(request.headers.get('User-Agent')),
|
||||||
|
'desc': xss_escape(request.form.get('username')),
|
||||||
|
'uid': uid,
|
||||||
|
'success': int(is_access)
|
||||||
|
|
||||||
|
}
|
||||||
|
log = AdminLog(
|
||||||
|
url=info.get('url'),
|
||||||
|
ip=info.get('ip'),
|
||||||
|
user_agent=info.get('user_agent'),
|
||||||
|
desc=info.get('desc'),
|
||||||
|
uid=info.get('uid'),
|
||||||
|
method=info.get('method'),
|
||||||
|
success=info.get('success')
|
||||||
|
)
|
||||||
|
db.session.add(log)
|
||||||
|
db.session.flush()
|
||||||
|
db.session.commit()
|
||||||
|
return log.id
|
||||||
|
|
||||||
|
|
||||||
|
def admin_log(request, is_access):
|
||||||
|
info = {
|
||||||
|
'method': request.method,
|
||||||
|
'url': request.path,
|
||||||
|
'ip': request.remote_addr,
|
||||||
|
'user_agent': xss_escape(request.headers.get('User-Agent')),
|
||||||
|
'desc': xss_escape(str(dict(request.values))),
|
||||||
|
'uid': current_user.id,
|
||||||
|
'success': int(is_access)
|
||||||
|
|
||||||
|
}
|
||||||
|
log = AdminLog(
|
||||||
|
url=info.get('url'),
|
||||||
|
ip=info.get('ip'),
|
||||||
|
user_agent=info.get('user_agent'),
|
||||||
|
desc=info.get('desc'),
|
||||||
|
uid=info.get('uid'),
|
||||||
|
method=info.get('method'),
|
||||||
|
success=info.get('success')
|
||||||
|
)
|
||||||
|
db.session.add(log)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
return log.id
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import datetime
|
||||||
|
|
||||||
|
from marshmallow import Schema
|
||||||
|
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
|
||||||
|
|
||||||
|
from applications.extensions import db, ma
|
||||||
|
|
||||||
|
|
||||||
|
class LogicalDeleteMixin(object):
|
||||||
|
"""
|
||||||
|
class Test(db.Model,LogicalDeleteMixin):
|
||||||
|
__tablename__ = 'admin_test'
|
||||||
|
id = db.Column(db.Integer, primary_key=True, comment='角色ID')
|
||||||
|
|
||||||
|
Test.query.filter_by(id=1).soft_delete()
|
||||||
|
Test.query.logic_all()
|
||||||
|
"""
|
||||||
|
create_at = db.Column(db.DateTime, default=datetime.datetime.now, comment='创建时间')
|
||||||
|
update_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, comment='创建时间')
|
||||||
|
delete_at = db.Column(db.DateTime, comment='删除时间')
|
||||||
|
|
||||||
|
|
||||||
|
def auto_model_jsonify(data, model: db.Model):
|
||||||
|
"""
|
||||||
|
不需要建立schemas,直接使用orm的定义模型进行序列化
|
||||||
|
基本功能,待完善
|
||||||
|
示例
|
||||||
|
power_data = curd.auto_model_jsonify(model=Dept, data=dept)
|
||||||
|
"""
|
||||||
|
def get_model():
|
||||||
|
return model
|
||||||
|
|
||||||
|
class AutoSchema(SQLAlchemyAutoSchema):
|
||||||
|
class Meta(Schema):
|
||||||
|
model = get_model()
|
||||||
|
include_fk = True
|
||||||
|
include_relationships = True
|
||||||
|
load_instance = True
|
||||||
|
|
||||||
|
common_schema = AutoSchema(many=True) # 用已继承ma.ModelSchema类的自定制类生成序列化类
|
||||||
|
output = common_schema.dump(data)
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def model_to_dicts(schema: ma.Schema, data):
|
||||||
|
"""
|
||||||
|
:param schema: schema类
|
||||||
|
:param model: sqlalchemy查询结果
|
||||||
|
:return: 返回单个查询结果
|
||||||
|
"""
|
||||||
|
# 如果是分页器返回,需要传入model.items
|
||||||
|
common_schema = schema(many=True) # 用已继承ma.ModelSchema类的自定制类生成序列化类
|
||||||
|
output = common_schema.dump(data) # 生成可序列化对象
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def get_one_by_id(model: db.Model, id):
|
||||||
|
"""
|
||||||
|
:param model: 模型类
|
||||||
|
:param id: id
|
||||||
|
:return: 返回单个查询结果
|
||||||
|
"""
|
||||||
|
return model.query.filter_by(id=id).first()
|
||||||
|
|
||||||
|
|
||||||
|
def delete_one_by_id(model: db.Model, id):
|
||||||
|
"""
|
||||||
|
:param model: 模型类
|
||||||
|
:param id: id
|
||||||
|
:return: 返回单个查询结果
|
||||||
|
"""
|
||||||
|
r = model.query.filter_by(id=id).delete()
|
||||||
|
db.session.commit()
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
# 启动状态
|
||||||
|
def enable_status(model: db.Model, id):
|
||||||
|
enable = 1
|
||||||
|
role = model.query.filter_by(id=id).update({"enable": enable})
|
||||||
|
if role:
|
||||||
|
db.session.commit()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
# 停用状态
|
||||||
|
def disable_status(model: db.Model, id):
|
||||||
|
enable = 0
|
||||||
|
role = model.query.filter_by(id=id).update({"enable": enable})
|
||||||
|
if role:
|
||||||
|
db.session.commit()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
from sqlalchemy import and_
|
||||||
|
|
||||||
|
from applications.extensions import db
|
||||||
|
|
||||||
|
|
||||||
|
class ModelFilter:
|
||||||
|
"""
|
||||||
|
orm多参数构造器
|
||||||
|
"""
|
||||||
|
filter_field = {}
|
||||||
|
filter_list = []
|
||||||
|
|
||||||
|
type_exact = "exact"
|
||||||
|
type_neq = "neq"
|
||||||
|
type_greater = "greater"
|
||||||
|
type_less = "less"
|
||||||
|
type_vague = "vague"
|
||||||
|
type_contains = "contains"
|
||||||
|
type_between = "between"
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.filter_field = {}
|
||||||
|
self.filter_list = []
|
||||||
|
|
||||||
|
def exact(self, field_name, value):
|
||||||
|
"""
|
||||||
|
准确查询字段
|
||||||
|
:param field_name: 模型字段名称
|
||||||
|
:param value: 值
|
||||||
|
"""
|
||||||
|
if value and value != '':
|
||||||
|
self.filter_field[field_name] = {"data": value, "type": self.type_exact}
|
||||||
|
|
||||||
|
def neq(self, field_name, value):
|
||||||
|
"""
|
||||||
|
不等于查询字段
|
||||||
|
:param field_name: 模型字段名称
|
||||||
|
:param value: 值
|
||||||
|
"""
|
||||||
|
if value and value != '':
|
||||||
|
self.filter_field[field_name] = {"data": value, "type": self.type_neq}
|
||||||
|
|
||||||
|
def greater(self, field_name, value):
|
||||||
|
"""
|
||||||
|
大于查询字段
|
||||||
|
:param field_name: 模型字段名称
|
||||||
|
:param value: 值
|
||||||
|
"""
|
||||||
|
if value and value != '':
|
||||||
|
self.filter_field[field_name] = {"data": value, "type": self.type_greater}
|
||||||
|
|
||||||
|
def less(self, field_name, value):
|
||||||
|
"""
|
||||||
|
大于查询字段
|
||||||
|
:param field_name: 模型字段名称
|
||||||
|
:param value: 值
|
||||||
|
"""
|
||||||
|
if value and value != '':
|
||||||
|
self.filter_field[field_name] = {"data": value, "type": self.type_less}
|
||||||
|
|
||||||
|
def vague(self, field_name, value: str):
|
||||||
|
"""
|
||||||
|
模糊查询字段
|
||||||
|
:param field_name: 模型字段名称
|
||||||
|
:param value: 值
|
||||||
|
"""
|
||||||
|
if value and value != '':
|
||||||
|
self.filter_field[field_name] = {"data": ('%' + value + '%'), "type": self.type_vague}
|
||||||
|
|
||||||
|
def left_vague(self, field_name, value: str):
|
||||||
|
"""
|
||||||
|
左模糊查询字段
|
||||||
|
:param field_name: 模型字段名称
|
||||||
|
:param value: 值
|
||||||
|
"""
|
||||||
|
if value and value != '':
|
||||||
|
self.filter_field[field_name] = {"data": ('%' + value), "type": self.type_vague}
|
||||||
|
|
||||||
|
def right_vague(self, field_name, value: str):
|
||||||
|
"""
|
||||||
|
左模糊查询字段
|
||||||
|
:param field_name: 模型字段名称
|
||||||
|
:param value: 值
|
||||||
|
"""
|
||||||
|
if value and value != '':
|
||||||
|
self.filter_field[field_name] = {"data": (value + '%'), "type": self.type_vague}
|
||||||
|
|
||||||
|
def contains(self, field_name, value: str):
|
||||||
|
"""
|
||||||
|
包含查询字段
|
||||||
|
:param field_name: 模型字段名称
|
||||||
|
:param value: 值
|
||||||
|
"""
|
||||||
|
if value and value != '':
|
||||||
|
self.filter_field[field_name] = {"data": value, "type": self.type_contains}
|
||||||
|
|
||||||
|
def between(self, field_name, value1, value2):
|
||||||
|
"""
|
||||||
|
范围查询字段
|
||||||
|
:param field_name: 模型字段名称
|
||||||
|
:param value: 值
|
||||||
|
"""
|
||||||
|
if value1 and value2 and value1 != '' and value2 != '':
|
||||||
|
self.filter_field[field_name] = {"data": [value1, value2], "type": self.type_between}
|
||||||
|
|
||||||
|
def get_filter(self, model: db.Model):
|
||||||
|
"""
|
||||||
|
获取过滤条件
|
||||||
|
:param model: 模型字段名称
|
||||||
|
"""
|
||||||
|
for k, v in self.filter_field.items():
|
||||||
|
if v.get("type") == self.type_vague:
|
||||||
|
self.filter_list.append(getattr(model, k).like(v.get("data")))
|
||||||
|
if v.get("type") == self.type_contains:
|
||||||
|
self.filter_list.append(getattr(model, k).contains(v.get("data")))
|
||||||
|
if v.get("type") == self.type_exact:
|
||||||
|
self.filter_list.append(getattr(model, k) == v.get("data"))
|
||||||
|
if v.get("type") == self.type_neq:
|
||||||
|
self.filter_list.append(getattr(model, k) != v.get("data"))
|
||||||
|
if v.get("type") == self.type_greater:
|
||||||
|
self.filter_list.append(getattr(model, k) > v.get("data"))
|
||||||
|
if v.get("type") == self.type_less:
|
||||||
|
self.filter_list.append(getattr(model, k) < v.get("data"))
|
||||||
|
if v.get("type") == self.type_between:
|
||||||
|
self.filter_list.append(getattr(model, k).between(v.get("data")[0], v.get("data")[1]))
|
||||||
|
return and_(*self.filter_list)
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
import click
|
||||||
|
|
||||||
|
from applications.common.script.initdb import init_db
|
||||||
|
from applications.common.script.newmodular.new import NewViewModular
|
||||||
|
|
||||||
|
|
||||||
|
def init_script(app):
|
||||||
|
@app.cli.command()
|
||||||
|
def init():
|
||||||
|
init_db()
|
||||||
|
|
||||||
|
@app.cli.command()
|
||||||
|
@click.option('--type', prompt="请输入类型", help='新增的类型')
|
||||||
|
@click.option('--name', prompt="请输入新增的名称", help='新增的名称')
|
||||||
|
def new(type,name):
|
||||||
|
if type == 'view':
|
||||||
|
if name.count('/') > 1:
|
||||||
|
print("目前只支持二级目录,多级目录需要蓝图嵌套,本命令暂不支持,请手动创建")
|
||||||
|
quit()
|
||||||
|
if type == "view" and os.path.exists(f"applications/view/{name}.py"):
|
||||||
|
print(f'已经存在视图模块{name}.py')
|
||||||
|
quit()
|
||||||
|
NewViewModular(name=name).new_view()
|
||||||
|
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
from dotenv import dotenv_values
|
||||||
|
import sqlparse
|
||||||
|
import pymysql
|
||||||
|
config = dotenv_values('.flaskenv')
|
||||||
|
# MySql配置信息
|
||||||
|
HOST = config.get('MYSQL_HOST') or '127.0.0.1'
|
||||||
|
PORT = config.get('MYSQL_PORT') or 3306
|
||||||
|
DATABASE = config.get('MYSQL_DATABASE') or 'PearAdminFlask'
|
||||||
|
USERNAME = config.get('MYSQL_USERNAME') or 'root'
|
||||||
|
PASSWORD = config.get('MYSQL_PASSWORD') or '123456'
|
||||||
|
|
||||||
|
|
||||||
|
def is_exist_database():
|
||||||
|
db = pymysql.connect(host=HOST, port=int(PORT), user=USERNAME, password=PASSWORD, charset='utf8mb4')
|
||||||
|
cursor1 = db.cursor()
|
||||||
|
sql = "select * from information_schema.SCHEMATA WHERE SCHEMA_NAME = '%s' ; " % DATABASE
|
||||||
|
res = cursor1.execute(sql)
|
||||||
|
db.close()
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
def init_database():
|
||||||
|
db = pymysql.connect(host=HOST, port=int(PORT), user=USERNAME, password=PASSWORD, charset='utf8mb4')
|
||||||
|
cursor1 = db.cursor()
|
||||||
|
sql = "CREATE DATABASE IF NOT EXISTS %s CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;" % DATABASE
|
||||||
|
res = cursor1.execute(sql)
|
||||||
|
db.close()
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
def execute_fromfile(filename):
|
||||||
|
db = pymysql.connect(host=HOST, port=int(PORT), user=USERNAME, password=PASSWORD, database=DATABASE,
|
||||||
|
charset='utf8mb4')
|
||||||
|
fd = open(filename, 'r', encoding='utf-8')
|
||||||
|
cursor = db.cursor()
|
||||||
|
sqlfile = fd.read()
|
||||||
|
sqlfile = sqlparse.format(sqlfile, strip_comments=True).strip()
|
||||||
|
|
||||||
|
sqlcommamds = sqlfile.split(';')
|
||||||
|
|
||||||
|
for command in sqlcommamds:
|
||||||
|
try:
|
||||||
|
cursor.execute(command)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
except Exception as msg:
|
||||||
|
|
||||||
|
db.rollback()
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
def init_db():
|
||||||
|
if is_exist_database():
|
||||||
|
print('数据库已经存在,为防止误初始化,请手动删除 %s 数据库' % str(DATABASE))
|
||||||
|
return
|
||||||
|
if init_database():
|
||||||
|
print('数据库%s创建成功' % str(DATABASE))
|
||||||
|
execute_fromfile('test/pear.sql')
|
||||||
|
print('表创建成功')
|
||||||
|
print('欢迎使用pear-admin-flask,请使用 flask run 命令启动程序')
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
import jinja2
|
||||||
|
|
||||||
|
|
||||||
|
class NewViewModular():
|
||||||
|
|
||||||
|
def __init__(self, name):
|
||||||
|
self.name = name
|
||||||
|
|
||||||
|
def path_is_exists(self):
|
||||||
|
return os.path.exists(f"applications/view/{self.name.split('/')[0]}")
|
||||||
|
|
||||||
|
def new_dirs(self):
|
||||||
|
if not self.path_is_exists():
|
||||||
|
# 如果不存在则创建目录
|
||||||
|
|
||||||
|
# 创建目录操作函数
|
||||||
|
os.makedirs(f"applications/view/{self.name.split('/')[0]}")
|
||||||
|
|
||||||
|
print(self.name + ' 创建成功')
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def add_view(self):
|
||||||
|
# jinja渲染
|
||||||
|
templateLoader = jinja2.FileSystemLoader(searchpath='applications/common/script/newmodular/template/')
|
||||||
|
templateEnv = jinja2.Environment(loader=templateLoader)
|
||||||
|
TEMPLATE_FILE = "view"
|
||||||
|
template = templateEnv.get_template(TEMPLATE_FILE, )
|
||||||
|
templateVars = {"name": self.name}
|
||||||
|
outputText = template.render(templateVars)
|
||||||
|
with open(f"applications/view/{self.name}.py", "a", encoding='utf-8') as f:
|
||||||
|
f.write(outputText)
|
||||||
|
f.close()
|
||||||
|
|
||||||
|
def add_init(self):
|
||||||
|
# 判断__init__.py
|
||||||
|
if os.path.exists(f"applications/view/{self.name.split('/')[0]}/__init__.py"):
|
||||||
|
with open(f"applications/view/{self.name.split('/')[0]}/__init__.py", "r") as file:
|
||||||
|
lines = file.readlines()
|
||||||
|
print(lines)
|
||||||
|
file.close()
|
||||||
|
import_line_num = 0
|
||||||
|
for line in lines:
|
||||||
|
if 'def' in line:
|
||||||
|
import_line_num = lines.index(line) - 2
|
||||||
|
with open(f"applications/view/{self.name.split('/')[0]}/__init__.py", "w") as file:
|
||||||
|
lines.insert(import_line_num,
|
||||||
|
f"from applications.view.{self.name.replace('/', '.')} import {self.name.replace('/', '_')}\n")
|
||||||
|
print(lines)
|
||||||
|
lines.insert(len(lines) - 1, f" app.register_blueprint({self.name.replace('/', '_')})\n")
|
||||||
|
print(lines)
|
||||||
|
file.writelines(lines)
|
||||||
|
file.close()
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
templateLoader = jinja2.FileSystemLoader(searchpath='applications/common/script/newmodular/template/')
|
||||||
|
templateEnv = jinja2.Environment(loader=templateLoader)
|
||||||
|
TEMPLATE_FILE = "__init__"
|
||||||
|
template = templateEnv.get_template(TEMPLATE_FILE, )
|
||||||
|
templateVars = {"name": self.name}
|
||||||
|
output = template.render(templateVars)
|
||||||
|
with open(f"applications/view/{self.name.split('/')[0]}/__init__.py", "a", encoding='utf-8') as f:
|
||||||
|
f.write(output)
|
||||||
|
f.close()
|
||||||
|
self.add_root_init()
|
||||||
|
return True
|
||||||
|
|
||||||
|
def add_root_init(self):
|
||||||
|
with open(f"applications/view/__init__.py", "r") as file:
|
||||||
|
lines = file.readlines()
|
||||||
|
file.close()
|
||||||
|
import_line_num = 0
|
||||||
|
for line in lines:
|
||||||
|
if 'def' in line:
|
||||||
|
import_line_num = lines.index(line) - 2
|
||||||
|
with open(f"applications/view/__init__.py", "w") as file:
|
||||||
|
lines.insert(
|
||||||
|
import_line_num,
|
||||||
|
f"from applications.view.{self.name.split('/')[0]} import register_{self.name.split('/')[0]}_views\n")
|
||||||
|
print(lines)
|
||||||
|
lines.insert(len(lines) - 1, f" register_{self.name.split('/')[0]}_views(app)\n")
|
||||||
|
print(lines)
|
||||||
|
file.writelines(lines)
|
||||||
|
file.close()
|
||||||
|
|
||||||
|
def new_view(self):
|
||||||
|
self.new_dirs()
|
||||||
|
self.add_view()
|
||||||
|
self.add_init()
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
from flask import Flask
|
||||||
|
from applications.view.{{name.replace('/','.')}} import {{name.replace('/','_')}}
|
||||||
|
|
||||||
|
|
||||||
|
def register_{{name.split('/')[0]}}_views(app: Flask):
|
||||||
|
app.register_blueprint({{name.replace('/','_')}})
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
from flask import Blueprint
|
||||||
|
|
||||||
|
{{name.replace('/','_')}} = Blueprint('{{name.replace('/','_')}}', __name__, url_prefix='/{{name}}')
|
||||||
|
|
||||||
|
|
||||||
|
@{{name.replace('/','_')}}.route('/')
|
||||||
|
def index():
|
||||||
|
return "这是{{name}}路由"
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
from apscheduler.events import (
|
||||||
|
EVENT_JOB_ADDED,
|
||||||
|
EVENT_JOB_ERROR,
|
||||||
|
EVENT_JOB_EXECUTED,
|
||||||
|
EVENT_JOB_MISSED,
|
||||||
|
EVENT_JOB_REMOVED,
|
||||||
|
EVENT_JOB_SUBMITTED,
|
||||||
|
)
|
||||||
|
|
||||||
|
from applications.extensions.init_apscheduler import scheduler
|
||||||
|
|
||||||
|
|
||||||
|
def job_missed(event):
|
||||||
|
"""Job missed event."""
|
||||||
|
with scheduler.app.app_context():
|
||||||
|
print(event) # noqa: T001
|
||||||
|
|
||||||
|
|
||||||
|
def job_error(event):
|
||||||
|
"""Job error event."""
|
||||||
|
with scheduler.app.app_context():
|
||||||
|
print(event) # noqa: T001
|
||||||
|
|
||||||
|
|
||||||
|
def job_executed(event):
|
||||||
|
"""Job executed event."""
|
||||||
|
with scheduler.app.app_context():
|
||||||
|
print(event) # noqa: T001
|
||||||
|
|
||||||
|
|
||||||
|
def job_added(event):
|
||||||
|
"""Job added event."""
|
||||||
|
with scheduler.app.app_context():
|
||||||
|
print(event) # noqa: T001
|
||||||
|
|
||||||
|
|
||||||
|
def job_removed(event):
|
||||||
|
"""Job removed event."""
|
||||||
|
with scheduler.app.app_context():
|
||||||
|
print(event) # noqa: T001
|
||||||
|
|
||||||
|
|
||||||
|
def job_submitted(event):
|
||||||
|
"""Job scheduled to run event."""
|
||||||
|
with scheduler.app.app_context():
|
||||||
|
print(event) # noqa: T001
|
||||||
|
|
||||||
|
|
||||||
|
scheduler.add_listener(job_missed, EVENT_JOB_MISSED)
|
||||||
|
scheduler.add_listener(job_error, EVENT_JOB_ERROR)
|
||||||
|
scheduler.add_listener(job_executed, EVENT_JOB_EXECUTED)
|
||||||
|
scheduler.add_listener(job_added, EVENT_JOB_ADDED)
|
||||||
|
scheduler.add_listener(job_removed, EVENT_JOB_REMOVED)
|
||||||
|
scheduler.add_listener(job_submitted, EVENT_JOB_SUBMITTED)
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import datetime
|
||||||
|
|
||||||
|
task_list = ['task2', 'task3', 'task4']
|
||||||
|
|
||||||
|
|
||||||
|
def task2(a, b):
|
||||||
|
print(f'定时任务_1_{a},{b},{datetime.datetime.now()}')
|
||||||
|
|
||||||
|
|
||||||
|
def task3(a, b):
|
||||||
|
print(f'定时任务_2_{a}{b}{datetime.datetime.now()}')
|
||||||
|
|
||||||
|
|
||||||
|
def task4(a, b):
|
||||||
|
print(f'定时任务_4_{a}{b}{datetime.datetime.now()}')
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
from captcha.image import ImageCaptcha
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
from random import choices
|
||||||
|
|
||||||
|
|
||||||
|
def gen_captcha(content='2345689abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ'):
|
||||||
|
""" 生成验证码 """
|
||||||
|
image = ImageCaptcha()
|
||||||
|
# 获取字符串
|
||||||
|
captcha_text = "".join(choices(content, k=4)).lower()
|
||||||
|
# 生成图像
|
||||||
|
captcha_image = Image.open(image.generate(captcha_text))
|
||||||
|
return captcha_text, captcha_image
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
from flask import jsonify
|
||||||
|
|
||||||
|
|
||||||
|
def success_api(msg: str = "成功"):
|
||||||
|
""" 成功响应 默认值”成功“ """
|
||||||
|
return jsonify(success=True, msg=msg)
|
||||||
|
|
||||||
|
|
||||||
|
def fail_api(msg: str = "失败"):
|
||||||
|
""" 失败响应 默认值“失败” """
|
||||||
|
return jsonify(success=False, msg=msg)
|
||||||
|
|
||||||
|
|
||||||
|
def table_api(msg: str = "", count=0, data=None, limit=10):
|
||||||
|
""" 动态表格渲染响应 """
|
||||||
|
res = {
|
||||||
|
'msg': msg,
|
||||||
|
'code': 0,
|
||||||
|
'data': data,
|
||||||
|
'count': count,
|
||||||
|
'limit': limit
|
||||||
|
|
||||||
|
}
|
||||||
|
return jsonify(res)
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
from flask_mail import Message
|
||||||
|
|
||||||
|
from applications.extensions.init_mail import mail
|
||||||
|
|
||||||
|
|
||||||
|
# send_mail(subject='title', recipients=['123@qq.com'], content='body')
|
||||||
|
def send_mail(subject, recipients, content):
|
||||||
|
try:
|
||||||
|
message = Message(subject=subject, recipients=recipients, body=content)
|
||||||
|
mail.send(message)
|
||||||
|
except Exception as e:
|
||||||
|
print('邮箱发送出错了')
|
||||||
|
raise
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
from functools import wraps
|
||||||
|
from flask import abort, request, jsonify, session
|
||||||
|
from flask_login import login_required
|
||||||
|
from applications.common.admin_log import admin_log
|
||||||
|
|
||||||
|
|
||||||
|
def authorize(power: str, log: bool = False):
|
||||||
|
def decorator(func):
|
||||||
|
@login_required
|
||||||
|
@wraps(func)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
if not power in session.get('permissions'):
|
||||||
|
if log:
|
||||||
|
admin_log(request=request, is_access=False)
|
||||||
|
if request.method == 'GET':
|
||||||
|
abort(403)
|
||||||
|
else:
|
||||||
|
return jsonify(success=False, msg="权限不足!")
|
||||||
|
if log:
|
||||||
|
admin_log(request=request, is_access=True)
|
||||||
|
return func(*args, **kwargs)
|
||||||
|
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
return decorator
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import os
|
||||||
|
from flask import current_app
|
||||||
|
from sqlalchemy import desc
|
||||||
|
from applications.extensions import db
|
||||||
|
from applications.extensions.init_upload import photos
|
||||||
|
from applications.models import Photo
|
||||||
|
from applications.schemas import PhotoOutSchema
|
||||||
|
from applications.common.curd import model_to_dicts
|
||||||
|
|
||||||
|
|
||||||
|
def get_photo(page, limit):
|
||||||
|
photo = Photo.query.order_by(desc(Photo.create_time)).paginate(page=page, per_page=limit, error_out=False)
|
||||||
|
count = Photo.query.count()
|
||||||
|
data = model_to_dicts(schema=PhotoOutSchema, data=photo.items)
|
||||||
|
return data, count
|
||||||
|
|
||||||
|
|
||||||
|
def upload_one(photo, mime):
|
||||||
|
filename = photos.save(photo)
|
||||||
|
file_url = '/_uploads/photos/'+filename
|
||||||
|
# file_url = photos.url(filename)
|
||||||
|
upload_url = current_app.config.get("UPLOADED_PHOTOS_DEST")
|
||||||
|
size = os.path.getsize(upload_url + '/' + filename)
|
||||||
|
photo = Photo(name=filename, href=file_url, mime=mime, size=size)
|
||||||
|
db.session.add(photo)
|
||||||
|
db.session.commit()
|
||||||
|
return file_url
|
||||||
|
|
||||||
|
|
||||||
|
def delete_photo_by_id(_id):
|
||||||
|
photo_name = Photo.query.filter_by(id=_id).first().name
|
||||||
|
photo = Photo.query.filter_by(id=_id).delete()
|
||||||
|
db.session.commit()
|
||||||
|
upload_url = current_app.config.get("UPLOADED_PHOTOS_DEST")
|
||||||
|
os.remove(upload_url + '/' + photo_name)
|
||||||
|
return photo
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# xss过滤
|
||||||
|
from flask import abort, make_response, jsonify
|
||||||
|
|
||||||
|
|
||||||
|
def xss_escape(s: str):
|
||||||
|
if s is None:
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
return s.replace("&", "&").replace(">", ">").replace("<", "<").replace("'", "'").replace('"',
|
||||||
|
""")
|
||||||
|
|
||||||
|
|
||||||
|
def check_data(schema, data):
|
||||||
|
errors = schema.validate(data)
|
||||||
|
for k, v in errors.items():
|
||||||
|
for i in v:
|
||||||
|
# print("{}{}".format(k, i))
|
||||||
|
msg = "{}{}".format(k, i)
|
||||||
|
if errors:
|
||||||
|
abort(make_response(jsonify(result=False, msg=msg), 200))
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
from .config import config
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from urllib.parse import quote_plus as urlquote
|
||||||
|
|
||||||
|
|
||||||
|
class BaseConfig:
|
||||||
|
|
||||||
|
SYSTEM_NAME = os.getenv('SYSTEM_NAME', 'Pear Admin')
|
||||||
|
# 主题面板的链接列表配置
|
||||||
|
SYSTEM_PANEL_LINKS = [
|
||||||
|
{
|
||||||
|
"icon": "layui-icon layui-icon-auz",
|
||||||
|
"title": "官方网站",
|
||||||
|
"href": "http://www.pearadmin.com"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"icon": "layui-icon layui-icon-auz",
|
||||||
|
"title": "开发文档",
|
||||||
|
"href": "http://www.pearadmin.com"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"icon": "layui-icon layui-icon-auz",
|
||||||
|
"title": "开源地址",
|
||||||
|
"href": "https://gitee.com/Jmysy/Pear-Admin-Layui"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
UPLOADED_PHOTOS_DEST = 'static/upload'
|
||||||
|
UPLOADED_FILES_ALLOW = ['gif', 'jpg']
|
||||||
|
|
||||||
|
# JSON配置
|
||||||
|
JSON_AS_ASCII = False
|
||||||
|
|
||||||
|
SECRET_KEY = os.getenv('SECRET_KEY', 'dev key')
|
||||||
|
|
||||||
|
# redis配置
|
||||||
|
REDIS_HOST = os.getenv('REDIS_HOST') or "127.0.0.1"
|
||||||
|
REDIS_PORT = int(os.getenv('REDIS_PORT') or 6379)
|
||||||
|
|
||||||
|
# mysql 配置
|
||||||
|
MYSQL_USERNAME = os.getenv('MYSQL_USERNAME') or "root"
|
||||||
|
MYSQL_PASSWORD = os.getenv('MYSQL_PASSWORD') or "123456"
|
||||||
|
MYSQL_HOST = os.getenv('MYSQL_HOST') or "127.0.0.1"
|
||||||
|
MYSQL_PORT = int(os.getenv('MYSQL_PORT') or 3306)
|
||||||
|
MYSQL_DATABASE = os.getenv('MYSQL_DATABASE') or "PearAdminFlask"
|
||||||
|
|
||||||
|
# mysql 数据库的配置信息
|
||||||
|
SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{MYSQL_USERNAME}:{urlquote(MYSQL_PASSWORD)}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DATABASE}?charset=utf8mb4"
|
||||||
|
|
||||||
|
# 默认日志等级
|
||||||
|
LOG_LEVEL = logging.WARN
|
||||||
|
#
|
||||||
|
MAIL_SERVER = os.getenv('MAIL_SERVER') or 'smtp.qq.com'
|
||||||
|
MAIL_USE_TLS = False
|
||||||
|
MAIL_USE_SSL = True
|
||||||
|
MAIL_PORT = 465
|
||||||
|
MAIL_USERNAME = os.getenv('MAIL_USERNAME') or '123@qq.com'
|
||||||
|
MAIL_PASSWORD = os.getenv('MAIL_PASSWORD') or 'XXXXX' # 生成的授权码
|
||||||
|
# 默认发件人的邮箱,这里填写和MAIL_USERNAME一致即可
|
||||||
|
MAIL_DEFAULT_SENDER = ('pear admin', os.getenv('MAIL_USERNAME') or '123@qq.com')
|
||||||
|
|
||||||
|
|
||||||
|
class TestingConfig(BaseConfig):
|
||||||
|
""" 测试配置 """
|
||||||
|
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:' # 内存数据库
|
||||||
|
|
||||||
|
|
||||||
|
class DevelopmentConfig(BaseConfig):
|
||||||
|
""" 开发配置 """
|
||||||
|
SQLALCHEMY_TRACK_MODIFICATIONS = True
|
||||||
|
SQLALCHEMY_ECHO = False
|
||||||
|
|
||||||
|
|
||||||
|
class ProductionConfig(BaseConfig):
|
||||||
|
"""生成环境配置"""
|
||||||
|
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||||
|
SQLALCHEMY_ECHO = False
|
||||||
|
SQLALCHEMY_POOL_RECYCLE = 8
|
||||||
|
|
||||||
|
LOG_LEVEL = logging.ERROR
|
||||||
|
|
||||||
|
|
||||||
|
config = {
|
||||||
|
'development': DevelopmentConfig,
|
||||||
|
'testing': TestingConfig,
|
||||||
|
'production': ProductionConfig
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
from .init_sqlalchemy import db, ma, init_databases
|
||||||
|
from .init_login import init_login_manager
|
||||||
|
from .init_debug_tool import init_debug_tool
|
||||||
|
from .init_template_directives import init_template_directives
|
||||||
|
from .init_error_views import init_error_views
|
||||||
|
from .init_mail import init_mail
|
||||||
|
from .init_apscheduler import init_scheduler
|
||||||
|
from .init_upload import init_upload
|
||||||
|
from .init_dotenv import init_dotenv
|
||||||
|
|
||||||
|
|
||||||
|
def init_plugs(app: Flask) -> None:
|
||||||
|
# init_debug_tool(app)
|
||||||
|
init_login_manager(app)
|
||||||
|
init_databases(app)
|
||||||
|
init_template_directives(app)
|
||||||
|
init_error_views(app)
|
||||||
|
init_mail(app)
|
||||||
|
init_scheduler(app)
|
||||||
|
init_upload(app)
|
||||||
|
init_dotenv()
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
from flask import Flask
|
||||||
|
from flask_apscheduler import APScheduler
|
||||||
|
|
||||||
|
scheduler = APScheduler()
|
||||||
|
|
||||||
|
|
||||||
|
def init_scheduler(app: Flask):
|
||||||
|
scheduler.init_app(app)
|
||||||
|
with app.app_context():
|
||||||
|
from applications.common.tasks import tasks
|
||||||
|
scheduler.start()
|
||||||
|
from applications.common.tasks import events
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
from flask import Flask
|
||||||
|
from flask_debugtoolbar import DebugToolbarExtension
|
||||||
|
|
||||||
|
|
||||||
|
def init_debug_tool(app: Flask):
|
||||||
|
toolbar = DebugToolbarExtension()
|
||||||
|
toolbar.init_app(app)
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import os
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
root_path = os.path.abspath(os.path.dirname(__file__)).split('applications')[0]
|
||||||
|
# dot_env_path = os.path.join(root_path, '.env')
|
||||||
|
flask_env_path = os.path.join(root_path, '.flaskenv')
|
||||||
|
|
||||||
|
|
||||||
|
# if os.path.exists(dot_env_path):
|
||||||
|
# load_dotenv(dot_env_path)
|
||||||
|
|
||||||
|
def init_dotenv():
|
||||||
|
if os.path.exists(flask_env_path):
|
||||||
|
load_dotenv(flask_env_path)
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
from flask import render_template, jsonify
|
||||||
|
|
||||||
|
|
||||||
|
def init_error_views(app):
|
||||||
|
@app.errorhandler(403)
|
||||||
|
def page_not_found(e):
|
||||||
|
return render_template('errors/403.html'), 403
|
||||||
|
|
||||||
|
@app.errorhandler(404)
|
||||||
|
def page_not_found(e):
|
||||||
|
return render_template('errors/404.html'), 404
|
||||||
|
|
||||||
|
@app.errorhandler(500)
|
||||||
|
def internal_server_error(e):
|
||||||
|
return render_template('errors/500.html'), 500
|
||||||
|
|
||||||
|
# Return validation errors as JSON
|
||||||
|
@app.errorhandler(422)
|
||||||
|
@app.errorhandler(400)
|
||||||
|
def handle_error(err):
|
||||||
|
headers = err.data.get("headers", None)
|
||||||
|
messages = err.data.get("messages", ["Invalid request."]).get('json')
|
||||||
|
print(err.data.get("messages"))
|
||||||
|
print(messages.items())
|
||||||
|
msg = ''
|
||||||
|
|
||||||
|
for i in messages.items():
|
||||||
|
msg = str(i[0]) + str(i[1][0])
|
||||||
|
break
|
||||||
|
|
||||||
|
if headers:
|
||||||
|
return jsonify({"success": False, "msg": msg})
|
||||||
|
else:
|
||||||
|
return jsonify({"success": False, "msg": msg})
|
||||||
@@ -5,11 +5,11 @@ def init_login_manager(app):
|
|||||||
login_manager = LoginManager()
|
login_manager = LoginManager()
|
||||||
login_manager.init_app(app)
|
login_manager.init_app(app)
|
||||||
|
|
||||||
login_manager.login_view = 'index.login'
|
login_manager.login_view = 'passport.login'
|
||||||
login_manager.login_message = u'请登录以访问此页面'
|
login_manager.login_message = u'请登录以访问此页面'
|
||||||
|
|
||||||
@login_manager.user_loader
|
@login_manager.user_loader
|
||||||
def load_user(user_id):
|
def load_user(user_id):
|
||||||
from models import UserModel
|
from applications.models import User
|
||||||
user = UserModel.query.get(int(user_id))
|
user = User.query.get(int(user_id))
|
||||||
return user
|
return user
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
from flask import Flask
|
||||||
|
from flask_mail import Mail
|
||||||
|
|
||||||
|
mail = Mail()
|
||||||
|
|
||||||
|
|
||||||
|
def init_mail(app: Flask):
|
||||||
|
mail.init_app(app)
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import datetime
|
||||||
|
|
||||||
|
from flask import Flask, request
|
||||||
|
from flask_sqlalchemy import SQLAlchemy, BaseQuery
|
||||||
|
from flask_marshmallow import Marshmallow
|
||||||
|
from marshmallow import fields
|
||||||
|
from marshmallow.validate import (
|
||||||
|
URL, Email, Range, Length, Equal, Regexp,
|
||||||
|
Predicate, NoneOf, OneOf, ContainsOnly
|
||||||
|
)
|
||||||
|
|
||||||
|
URL.default_message = '无效的链接'
|
||||||
|
Email.default_message = '无效的邮箱地址'
|
||||||
|
Range.message_min = '不能小于{min}'
|
||||||
|
Range.message_max = '不能小于{max}'
|
||||||
|
Range.message_all = '不能超过{min}和{max}这个范围'
|
||||||
|
Length.message_min = '长度不得小于{min}位'
|
||||||
|
Length.message_max = '长度不得大于{max}位'
|
||||||
|
Length.message_all = '长度不能超过{min}和{max}这个范围'
|
||||||
|
Length.message_equal = '长度必须等于{equal}位'
|
||||||
|
Equal.default_message = '必须等于{other}'
|
||||||
|
Regexp.default_message = '非法输入'
|
||||||
|
Predicate.default_message = '非法输入'
|
||||||
|
NoneOf.default_message = '非法输入'
|
||||||
|
OneOf.default_message = '无效的选择'
|
||||||
|
ContainsOnly.default_message = '一个或多个无效的选择'
|
||||||
|
|
||||||
|
fields.Field.default_error_messages = {
|
||||||
|
"required": "缺少必要数据",
|
||||||
|
"null": "数据不能为空",
|
||||||
|
"validator_failed": "非法数据",
|
||||||
|
}
|
||||||
|
|
||||||
|
fields.Str.default_error_messages = {
|
||||||
|
'invalid': "不是合法文本"
|
||||||
|
}
|
||||||
|
|
||||||
|
fields.Int.default_error_messages = {
|
||||||
|
"invalid": "不是合法整数"
|
||||||
|
}
|
||||||
|
|
||||||
|
fields.Number.default_error_messages = {
|
||||||
|
"invalid": "不是合法数字"
|
||||||
|
}
|
||||||
|
|
||||||
|
fields.Boolean.default_error_messages = {
|
||||||
|
"invalid": "不是合法布尔值"
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class Query(BaseQuery):
|
||||||
|
def soft_delete(self):
|
||||||
|
return self.update({"delete_at": datetime.datetime.now()})
|
||||||
|
|
||||||
|
def logic_all(self):
|
||||||
|
return self.filter_by(delete_at=None).all()
|
||||||
|
|
||||||
|
def all_json(self, schema: Marshmallow().Schema):
|
||||||
|
return schema(many=True).dump(self.all())
|
||||||
|
|
||||||
|
def layui_paginate(self):
|
||||||
|
return self.paginate(page=request.args.get('page', type=int),
|
||||||
|
per_page=request.args.get('limit', type=int),
|
||||||
|
error_out=False)
|
||||||
|
|
||||||
|
def layui_paginate_json(self, schema: Marshmallow().Schema):
|
||||||
|
"""
|
||||||
|
返回dict
|
||||||
|
"""
|
||||||
|
_res = self.paginate(
|
||||||
|
page=request.args.get('page', type=int),
|
||||||
|
per_page=request.args.get('limit', type=int),
|
||||||
|
error_out=False
|
||||||
|
)
|
||||||
|
return schema(many=True).dump(_res.items), _res.total, _res.page, _res.per_page
|
||||||
|
|
||||||
|
def layui_paginate_db_json(self):
|
||||||
|
"""
|
||||||
|
db.query(A.name).layui_paginate_db_json()
|
||||||
|
"""
|
||||||
|
_res = self.paginate(page=request.args.get('page', type=int),
|
||||||
|
per_page=request.args.get('limit', type=int),
|
||||||
|
error_out=False)
|
||||||
|
return [dict(i) for i in _res.items], _res.total
|
||||||
|
|
||||||
|
|
||||||
|
db = SQLAlchemy(query_class=Query)
|
||||||
|
ma = Marshmallow()
|
||||||
|
|
||||||
|
|
||||||
|
def init_databases(app: Flask):
|
||||||
|
db.init_app(app)
|
||||||
|
ma.init_app(app)
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
from flask import Flask
|
||||||
|
from flask_uploads import configure_uploads
|
||||||
|
from flask_uploads import UploadSet, IMAGES
|
||||||
|
|
||||||
|
photos = UploadSet('photos', IMAGES)
|
||||||
|
|
||||||
|
|
||||||
|
def init_upload(app: Flask):
|
||||||
|
configure_uploads(app, photos)
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
from marshmallow import EXCLUDE
|
||||||
|
from webargs.flaskparser import FlaskParser
|
||||||
|
|
||||||
|
|
||||||
|
class Parser(FlaskParser):
|
||||||
|
DEFAULT_UNKNOWN_BY_LOCATION = {"query": EXCLUDE}
|
||||||
|
|
||||||
|
|
||||||
|
parser = Parser()
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
from .admin_dept import Dept
|
||||||
|
from .admin_dict import DictType, DictData
|
||||||
|
from .admin_log import AdminLog
|
||||||
|
from .admin_photo import Photo
|
||||||
|
from .admin_power import Power
|
||||||
|
from .admin_role import Role
|
||||||
|
from .admin_role_power import role_power
|
||||||
|
from .admin_user import User
|
||||||
|
from .admin_user_role import user_role
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import datetime
|
||||||
|
from applications.extensions import db
|
||||||
|
|
||||||
|
|
||||||
|
class Dept(db.Model):
|
||||||
|
__tablename__ = 'admin_dept'
|
||||||
|
id = db.Column(db.Integer, primary_key=True, comment="部门ID")
|
||||||
|
parent_id = db.Column(db.Integer, comment="父级编号")
|
||||||
|
dept_name = db.Column(db.String(50), comment="部门名称")
|
||||||
|
sort = db.Column(db.Integer, comment="排序")
|
||||||
|
leader = db.Column(db.String(50), comment="负责人")
|
||||||
|
phone = db.Column(db.String(20), comment="联系方式")
|
||||||
|
email = db.Column(db.String(50), comment="邮箱")
|
||||||
|
status = db.Column(db.Integer, comment='状态(1开启,0关闭)')
|
||||||
|
remark = db.Column(db.Text, comment="备注")
|
||||||
|
address = db.Column(db.String(255), comment="详细地址")
|
||||||
|
create_at = db.Column(db.DateTime, default=datetime.datetime.now, comment='创建时间')
|
||||||
|
update_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, comment='创建时间')
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import datetime
|
||||||
|
from applications.extensions import db
|
||||||
|
|
||||||
|
|
||||||
|
class DictType(db.Model):
|
||||||
|
__tablename__ = 'admin_dict_type'
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
type_name = db.Column(db.String(255), comment='字典类型名称')
|
||||||
|
type_code = db.Column(db.String(255), comment='字典类型标识')
|
||||||
|
description = db.Column(db.String(255), comment='字典类型描述')
|
||||||
|
enable = db.Column(db.Integer, comment='是否开启')
|
||||||
|
create_time = db.Column(db.DateTime, default=datetime.datetime.now, comment='创建时间')
|
||||||
|
update_time = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, comment='更新时间')
|
||||||
|
|
||||||
|
|
||||||
|
class DictData(db.Model):
|
||||||
|
__tablename__ = 'admin_dict_data'
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
data_label = db.Column(db.String(255), comment='字典类型名称')
|
||||||
|
data_value = db.Column(db.String(255), comment='字典类型标识')
|
||||||
|
type_code = db.Column(db.String(255), comment='字典类型描述')
|
||||||
|
is_default = db.Column(db.Integer, comment='是否默认')
|
||||||
|
enable = db.Column(db.Integer, comment='是否开启')
|
||||||
|
remark = db.Column(db.String(255), comment='备注')
|
||||||
|
create_time = db.Column(db.DateTime, default=datetime.datetime.now, comment='创建时间')
|
||||||
|
update_time = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, comment='更新时间')
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import datetime
|
||||||
|
from applications.extensions import db
|
||||||
|
|
||||||
|
class AdminLog(db.Model):
|
||||||
|
__tablename__ = 'admin_admin_log'
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
method = db.Column(db.String(10))
|
||||||
|
uid = db.Column(db.Integer)
|
||||||
|
url = db.Column(db.String(255))
|
||||||
|
desc = db.Column(db.Text)
|
||||||
|
ip = db.Column(db.String(255))
|
||||||
|
success = db.Column(db.Integer)
|
||||||
|
user_agent = db.Column(db.Text)
|
||||||
|
create_time = db.Column(db.DateTime, default=datetime.datetime.now)
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import datetime
|
||||||
|
from applications.extensions import db
|
||||||
|
|
||||||
|
|
||||||
|
class Photo(db.Model):
|
||||||
|
__tablename__ = 'admin_photo'
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
name = db.Column(db.String(255), nullable=False)
|
||||||
|
href = db.Column(db.String(255))
|
||||||
|
mime = db.Column(db.CHAR(50), nullable=False)
|
||||||
|
size = db.Column(db.CHAR(30), nullable=False)
|
||||||
|
create_time = db.Column(db.DateTime, default=datetime.datetime.now)
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import datetime
|
||||||
|
from applications.extensions import db
|
||||||
|
|
||||||
|
|
||||||
|
class Power(db.Model):
|
||||||
|
__tablename__ = 'admin_power'
|
||||||
|
id = db.Column(db.Integer, primary_key=True, comment='权限编号')
|
||||||
|
name = db.Column(db.String(255), comment='权限名称')
|
||||||
|
type = db.Column(db.String(1), comment='权限类型')
|
||||||
|
code = db.Column(db.String(30), comment='权限标识')
|
||||||
|
url = db.Column(db.String(255), comment='权限路径')
|
||||||
|
open_type = db.Column(db.String(10), comment='打开方式')
|
||||||
|
parent_id = db.Column(db.Integer, comment='父类编号')
|
||||||
|
icon = db.Column(db.String(128), comment='图标')
|
||||||
|
sort = db.Column(db.Integer, comment='排序')
|
||||||
|
create_time = db.Column(db.DateTime, default=datetime.datetime.now, comment='创建时间')
|
||||||
|
update_time = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, comment='更新时间')
|
||||||
|
enable = db.Column(db.Integer, comment='是否开启')
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import datetime
|
||||||
|
from applications.extensions import db
|
||||||
|
|
||||||
|
|
||||||
|
class Role(db.Model):
|
||||||
|
__tablename__ = 'admin_role'
|
||||||
|
id = db.Column(db.Integer, primary_key=True, comment='角色ID')
|
||||||
|
name = db.Column(db.String(255), comment='角色名称')
|
||||||
|
code = db.Column(db.String(255), comment='角色标识')
|
||||||
|
enable = db.Column(db.Integer, comment='是否启用')
|
||||||
|
remark = db.Column(db.String(255), comment='备注')
|
||||||
|
details = db.Column(db.String(255), comment='详情')
|
||||||
|
sort = db.Column(db.Integer, comment='排序')
|
||||||
|
create_time = db.Column(db.DateTime, default=datetime.datetime.now, comment='创建时间')
|
||||||
|
update_time = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, comment='更新时间')
|
||||||
|
power = db.relationship('Power', secondary="admin_role_power", backref=db.backref('role'))
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
from applications.extensions import db
|
||||||
|
|
||||||
|
# 创建中间表
|
||||||
|
role_power = db.Table(
|
||||||
|
"admin_role_power", # 中间表名称
|
||||||
|
db.Column("id", db.Integer, primary_key=True, autoincrement=True, comment='标识'), # 主键
|
||||||
|
db.Column("power_id", db.Integer, db.ForeignKey("admin_power.id"), comment='用户编号'), # 属性 外键
|
||||||
|
db.Column("role_id", db.Integer, db.ForeignKey("admin_role.id"), comment='角色编号'), # 属性 外键
|
||||||
|
)
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import datetime
|
||||||
|
from flask_login import UserMixin
|
||||||
|
from werkzeug.security import generate_password_hash, check_password_hash
|
||||||
|
from applications.extensions import db
|
||||||
|
|
||||||
|
|
||||||
|
class User(db.Model, UserMixin):
|
||||||
|
__tablename__ = 'admin_user'
|
||||||
|
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='用户ID')
|
||||||
|
username = db.Column(db.String(20), comment='用户名')
|
||||||
|
realname = db.Column(db.String(20), comment='真实名字')
|
||||||
|
avatar = db.Column(db.String(255), comment='头像', default="/static/admin/admin/images/avatar.jpg")
|
||||||
|
remark = db.Column(db.String(255), comment='备注')
|
||||||
|
password_hash = db.Column(db.String(128), comment='哈希密码')
|
||||||
|
enable = db.Column(db.Integer, default=0, comment='启用')
|
||||||
|
dept_id = db.Column(db.Integer, comment='部门id')
|
||||||
|
create_at = db.Column(db.DateTime, default=datetime.datetime.now, comment='创建时间')
|
||||||
|
update_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, comment='创建时间')
|
||||||
|
role = db.relationship('Role', secondary="admin_user_role", backref=db.backref('user'), lazy='dynamic')
|
||||||
|
|
||||||
|
def set_password(self, password):
|
||||||
|
self.password_hash = generate_password_hash(password)
|
||||||
|
|
||||||
|
def validate_password(self, password):
|
||||||
|
return check_password_hash(self.password_hash, password)
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
from applications.extensions import db
|
||||||
|
|
||||||
|
# 创建中间表
|
||||||
|
user_role = db.Table(
|
||||||
|
"admin_user_role", # 中间表名称
|
||||||
|
db.Column("id", db.Integer, primary_key=True, autoincrement=True, comment='标识'), # 主键
|
||||||
|
db.Column("user_id", db.Integer, db.ForeignKey("admin_user.id"), comment='用户编号'), # 属性 外键
|
||||||
|
db.Column("role_id", db.Integer, db.ForeignKey("admin_role.id"), comment='角色编号'), # 属性 外键
|
||||||
|
)
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
from common import register_api
|
|
||||||
from .department import DepartmentsApi, DeptEnableAPI
|
|
||||||
from .rights import (
|
|
||||||
RightsApi, PowerApi, right_power_enable_resource,
|
|
||||||
admin_configs_resource, admin_menu_resource
|
|
||||||
)
|
|
||||||
from .roles import RoleRoleApi, RolePowerApi, role_deletes, role_enable_resource
|
|
||||||
|
|
||||||
|
|
||||||
def register_rights_api(api_bp):
|
|
||||||
register_api(DepartmentsApi, 'rights_dept_api', '/dept/department/', pk='_id', app=api_bp)
|
|
||||||
api_bp.add_url_rule('/dept/department/<int:_id>/status',
|
|
||||||
view_func=DeptEnableAPI.as_view('dept_status_api'),
|
|
||||||
methods=['PUT', ])
|
|
||||||
api_bp.add_url_rule('/rights/rights',
|
|
||||||
view_func=RightsApi.as_view('dept_rights_api'),
|
|
||||||
methods=['GET', 'DELETE'])
|
|
||||||
|
|
||||||
register_api(PowerApi, 'rights_power_api', '/rights/power/', pk='_id', app=api_bp)
|
|
||||||
api_bp.add_url_rule('/rights/configs',
|
|
||||||
endpoint='rights_config_api',
|
|
||||||
view_func=admin_configs_resource,
|
|
||||||
methods=['GET'])
|
|
||||||
api_bp.add_url_rule('/rights/menu',
|
|
||||||
endpoint='rights_menu_api',
|
|
||||||
view_func=admin_menu_resource,
|
|
||||||
methods=['GET'])
|
|
||||||
api_bp.add_url_rule('/rights/power/<int:_id>/<action>',
|
|
||||||
endpoint='rights_power_action_api',
|
|
||||||
view_func=right_power_enable_resource,
|
|
||||||
methods=['PUT'])
|
|
||||||
api_bp.add_url_rule('/roles/role',
|
|
||||||
endpoint='rights_roles_role_api',
|
|
||||||
view_func=role_deletes,
|
|
||||||
methods=['DELETE'])
|
|
||||||
|
|
||||||
register_api(RoleRoleApi, 'rights_role_api', '/roles/role/', pk='_id', app=api_bp)
|
|
||||||
register_api(RolePowerApi, 'rights_role_power_api', '/roles/role_power/', pk='_id', app=api_bp)
|
|
||||||
api_bp.add_url_rule('/roles/role/<int:_id>/status',
|
|
||||||
endpoint='rights_roles_enable_api',
|
|
||||||
view_func=role_enable_resource,
|
|
||||||
methods=['PUT'])
|
|
||||||
@@ -1,114 +0,0 @@
|
|||||||
import typing as t
|
|
||||||
|
|
||||||
from flask import jsonify
|
|
||||||
from flask.views import MethodView
|
|
||||||
from flask_pydantic import validate
|
|
||||||
from pydantic import BaseModel, Field
|
|
||||||
|
|
||||||
from common.utils.http import success_api, fail_api
|
|
||||||
from extensions import db
|
|
||||||
from models import DepartmentModel, UserModel
|
|
||||||
|
|
||||||
|
|
||||||
class DeptModel(BaseModel):
|
|
||||||
address: t.Optional[str]
|
|
||||||
dept_name: t.Optional[str] = Field(alias='deptName')
|
|
||||||
email: t.Optional[str]
|
|
||||||
leader: t.Optional[str]
|
|
||||||
parent_id: t.Optional[str] = Field(alias='parentId')
|
|
||||||
phone: t.Optional[str]
|
|
||||||
sort: t.Optional[int]
|
|
||||||
status: t.Optional[int]
|
|
||||||
|
|
||||||
|
|
||||||
class DepartmentsApi(MethodView):
|
|
||||||
|
|
||||||
def get(self, _id):
|
|
||||||
if _id:
|
|
||||||
dept = DepartmentModel.query.filter_by(id=_id).first()
|
|
||||||
dept_data = {
|
|
||||||
'id': dept.id,
|
|
||||||
'dept_name': dept.dept_name,
|
|
||||||
'leader': dept.leader,
|
|
||||||
'email': dept.email,
|
|
||||||
'phone': dept.phone,
|
|
||||||
'status': dept.status,
|
|
||||||
'sort': dept.sort,
|
|
||||||
'address': dept.address,
|
|
||||||
}
|
|
||||||
return dict(success=True, message='ok', dept=dept_data)
|
|
||||||
|
|
||||||
dept_data = DepartmentModel.query.order_by(DepartmentModel.sort).all()
|
|
||||||
# TODO dtree 需要返回状态信息
|
|
||||||
res = {
|
|
||||||
"status": {"code": 200, "message": "默认"},
|
|
||||||
"data": [
|
|
||||||
{
|
|
||||||
'deptId': item.id,
|
|
||||||
'parentId': item.parent_id,
|
|
||||||
'deptName': item.dept_name,
|
|
||||||
'sort': item.sort,
|
|
||||||
'leader': item.leader,
|
|
||||||
'phone': item.phone,
|
|
||||||
'email': item.email,
|
|
||||||
'status': item.status,
|
|
||||||
'comment': item.comment,
|
|
||||||
'address': item.address,
|
|
||||||
'create_at': item.create_at.strftime('%Y-%m-%d %H:%M:%S')
|
|
||||||
} for item in dept_data
|
|
||||||
]
|
|
||||||
}
|
|
||||||
return jsonify(res)
|
|
||||||
|
|
||||||
@validate()
|
|
||||||
def post(self, body: DeptModel):
|
|
||||||
dept = DepartmentModel(
|
|
||||||
parent_id=body.parent_id,
|
|
||||||
dept_name=body.dept_name,
|
|
||||||
sort=body.sort,
|
|
||||||
leader=body.leader,
|
|
||||||
phone=body.phone,
|
|
||||||
email=body.email,
|
|
||||||
status=body.status,
|
|
||||||
address=body.address
|
|
||||||
)
|
|
||||||
db.session.add(dept)
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
return success_api(message="成功")
|
|
||||||
|
|
||||||
@validate()
|
|
||||||
def put(self, _id, body: DeptModel):
|
|
||||||
data = {
|
|
||||||
"dept_name": body.dept_name,
|
|
||||||
"sort": body.sort,
|
|
||||||
"leader": body.leader,
|
|
||||||
"phone": body.phone,
|
|
||||||
"email": body.email,
|
|
||||||
"status": body.status,
|
|
||||||
"address": body.address
|
|
||||||
}
|
|
||||||
body = DepartmentModel.query.filter_by(id=_id).update(data)
|
|
||||||
if not body:
|
|
||||||
return fail_api(message="更新失败")
|
|
||||||
db.session.commit()
|
|
||||||
return success_api(message="更新成功")
|
|
||||||
|
|
||||||
def delete(self, _id):
|
|
||||||
ret = DepartmentModel.query.filter_by(id=_id).delete()
|
|
||||||
UserModel.query.filter_by(dept_id=_id).update({"dept_id": None})
|
|
||||||
db.session.commit()
|
|
||||||
if ret:
|
|
||||||
return success_api(message="删除成功")
|
|
||||||
return fail_api(message="删除失败")
|
|
||||||
|
|
||||||
|
|
||||||
class DeptEnableAPI(MethodView):
|
|
||||||
def put(self, _id):
|
|
||||||
d = DepartmentModel.query.get(_id)
|
|
||||||
if d:
|
|
||||||
d.status = not d.status
|
|
||||||
db.session.commit()
|
|
||||||
message = '修改成功'
|
|
||||||
return success_api(message=message)
|
|
||||||
return fail_api(message="出错啦")
|
|
||||||
@@ -1,278 +0,0 @@
|
|||||||
import copy
|
|
||||||
from collections import OrderedDict
|
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
from flask import request, jsonify, current_app
|
|
||||||
from flask.views import MethodView
|
|
||||||
from flask_login import current_user
|
|
||||||
from flask_pydantic import validate
|
|
||||||
from pydantic import BaseModel, Field
|
|
||||||
|
|
||||||
from common.utils.http import success_api, fail_api
|
|
||||||
from extensions import db
|
|
||||||
from models import RightModel, RoleModel
|
|
||||||
|
|
||||||
|
|
||||||
def get_render_config():
|
|
||||||
# 网站配置
|
|
||||||
config = {
|
|
||||||
'logo': {
|
|
||||||
# 网站名称
|
|
||||||
"title": current_app.config.get("SYSTEM_NAME"),
|
|
||||||
# 网站图标
|
|
||||||
"image": "/static/admin/admin/images/logo.png"
|
|
||||||
# 菜单配置
|
|
||||||
},
|
|
||||||
'menu': {
|
|
||||||
# 菜单数据来源
|
|
||||||
"data": "/api/v1/rights/menu",
|
|
||||||
"collaspe": True,
|
|
||||||
# 是否同时只打开一个菜单目录
|
|
||||||
"accordion": True,
|
|
||||||
"method": "GET",
|
|
||||||
# 是否开启多系统菜单模式
|
|
||||||
"control": False,
|
|
||||||
# 默认选中的菜单项
|
|
||||||
"select": "0",
|
|
||||||
# 是否开启异步菜单,false 时 data 属性设置为菜单数据,false 时为 json 文件或后端接口
|
|
||||||
"async": True
|
|
||||||
},
|
|
||||||
'tab': {
|
|
||||||
# 是否开启多选项卡
|
|
||||||
"muiltTab": True,
|
|
||||||
# 切换选项卡时,是否刷新页面状态
|
|
||||||
"keepState": True,
|
|
||||||
# 是否开启 Tab 记忆
|
|
||||||
"session": True,
|
|
||||||
# 最大可打开的选项卡数量
|
|
||||||
"tabMax": 30,
|
|
||||||
"index": {
|
|
||||||
# 标识 ID , 建议与菜单项中的 ID 一致
|
|
||||||
"id": "10",
|
|
||||||
# 页面地址
|
|
||||||
"href": "/admin/welcome",
|
|
||||||
# 标题
|
|
||||||
"title": "首页"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
'theme': {
|
|
||||||
# 默认主题色,对应 colors 配置中的 ID 标识
|
|
||||||
"defaultColor": "2",
|
|
||||||
# 默认的菜单主题 dark-theme 黑 / light-theme 白
|
|
||||||
"defaultMenu": "dark-theme",
|
|
||||||
# 是否允许用户切换主题,false 时关闭自定义主题面板
|
|
||||||
"allowCustom": True
|
|
||||||
},
|
|
||||||
'colors': [
|
|
||||||
{
|
|
||||||
"id": "1",
|
|
||||||
"color": "#2d8cf0"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "2",
|
|
||||||
"color": "#5FB878"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "3",
|
|
||||||
"color": "#1E9FFF"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "4",
|
|
||||||
"color": "#FFB800"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "5",
|
|
||||||
"color": "darkgray"
|
|
||||||
},
|
|
||||||
],
|
|
||||||
'links': current_app.config.get("SYSTEM_PANEL_LINKS"),
|
|
||||||
'other': {
|
|
||||||
# 主页动画时长
|
|
||||||
"keepLoad": 1200,
|
|
||||||
# 布局顶部主题
|
|
||||||
"autoHead": False
|
|
||||||
},
|
|
||||||
'header': False
|
|
||||||
}
|
|
||||||
return config
|
|
||||||
|
|
||||||
|
|
||||||
# 生成菜单树
|
|
||||||
def make_menu_tree():
|
|
||||||
role = current_user.role
|
|
||||||
powers = []
|
|
||||||
for i in role:
|
|
||||||
# 如果角色没有被启用就直接跳过
|
|
||||||
if i.enable == 0:
|
|
||||||
continue
|
|
||||||
# 变量角色用户的权限
|
|
||||||
for p in i.power:
|
|
||||||
# 如果权限关闭了就直接跳过
|
|
||||||
if p.enable == 0:
|
|
||||||
continue
|
|
||||||
# 一二级菜单
|
|
||||||
if p.type == 0 or p.type == 1:
|
|
||||||
powers.append(p)
|
|
||||||
|
|
||||||
power_dict = [
|
|
||||||
{
|
|
||||||
'id': item.id,
|
|
||||||
'title': item.name,
|
|
||||||
'type': item.type,
|
|
||||||
'code': item.code,
|
|
||||||
'href': item.url,
|
|
||||||
'openType': item.open_type,
|
|
||||||
'parent_id': item.parent_id,
|
|
||||||
'icon': item.icon,
|
|
||||||
'sort': item.sort,
|
|
||||||
'enable': item.enable,
|
|
||||||
} for item in powers
|
|
||||||
]
|
|
||||||
power_dict.sort(key=lambda x: x['id'], reverse=True)
|
|
||||||
|
|
||||||
menu_dict = OrderedDict()
|
|
||||||
for _dict in power_dict:
|
|
||||||
if _dict['id'] in menu_dict:
|
|
||||||
# 当前节点添加子节点
|
|
||||||
_dict['children'] = copy.deepcopy(menu_dict[_dict['id']])
|
|
||||||
_dict['children'].sort(key=lambda item: item['sort'])
|
|
||||||
# 删除子节点
|
|
||||||
del menu_dict[_dict['id']]
|
|
||||||
|
|
||||||
if _dict['parent_id'] not in menu_dict:
|
|
||||||
menu_dict[_dict['parent_id']] = [_dict]
|
|
||||||
else:
|
|
||||||
menu_dict[_dict['parent_id']].append(_dict)
|
|
||||||
|
|
||||||
return sorted(menu_dict.get(0), key=lambda item: item['sort'])
|
|
||||||
|
|
||||||
|
|
||||||
class PowerModel(BaseModel):
|
|
||||||
icon: str
|
|
||||||
open_type: Optional[str] = Field(alias='openType')
|
|
||||||
parent_id: Optional[str] = Field(alias='parentId')
|
|
||||||
power_code: Optional[str] = Field(alias='powerCode')
|
|
||||||
power_name: Optional[str] = Field(alias='powerName')
|
|
||||||
power_type: Optional[str] = Field(alias='powerType')
|
|
||||||
power_url: Optional[str] = Field(alias='powerUrl')
|
|
||||||
sort: Optional[int] = Field(alias='sort')
|
|
||||||
|
|
||||||
|
|
||||||
class RightsApi(MethodView):
|
|
||||||
def get(self):
|
|
||||||
"""获取选择父节点"""
|
|
||||||
|
|
||||||
power = RightModel.query.all()
|
|
||||||
# power_data = marshal(power, RightModel.fields())
|
|
||||||
power_data = [
|
|
||||||
{
|
|
||||||
'powerId': item.id,
|
|
||||||
'powerName': item.name,
|
|
||||||
'powerType': item.type,
|
|
||||||
'powerUrl': item.url,
|
|
||||||
'openType': item.open_type,
|
|
||||||
'parentId': item.parent_id,
|
|
||||||
'icon': item.icon,
|
|
||||||
'sort': item.sort,
|
|
||||||
'enable': item.enable,
|
|
||||||
} for item in power
|
|
||||||
]
|
|
||||||
power_data.append({"powerId": 0, "powerName": "顶级权限", "parentId": -1})
|
|
||||||
res = {
|
|
||||||
"status": {"code": 200, "message": "默认"},
|
|
||||||
"data": power_data
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
|
|
||||||
def delete(self):
|
|
||||||
ids = request.form.getlist('ids[]')
|
|
||||||
for id in ids:
|
|
||||||
role = RoleModel.query.filter_by(id=id).first()
|
|
||||||
# 删除该角色的权限和用户
|
|
||||||
role.power = []
|
|
||||||
role.user = []
|
|
||||||
|
|
||||||
r = RoleModel.query.filter_by(id=id).delete()
|
|
||||||
db.session.commit()
|
|
||||||
return success_api(message="批量删除成功")
|
|
||||||
|
|
||||||
|
|
||||||
class PowerApi(MethodView):
|
|
||||||
@validate()
|
|
||||||
def post(self, body: PowerModel):
|
|
||||||
power = RightModel(
|
|
||||||
icon=body.icon,
|
|
||||||
open_type=body.open_type,
|
|
||||||
parent_id=body.parent_id,
|
|
||||||
code=body.power_code,
|
|
||||||
name=body.power_name,
|
|
||||||
type=body.power_type,
|
|
||||||
url=body.power_url,
|
|
||||||
sort=body.sort,
|
|
||||||
enable=1
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
db.session.add(power)
|
|
||||||
db.session.commit()
|
|
||||||
except Exception as e:
|
|
||||||
print(e)
|
|
||||||
return fail_api(message='数据提交失败')
|
|
||||||
|
|
||||||
return success_api(message="成功")
|
|
||||||
|
|
||||||
def delete(self, _id):
|
|
||||||
# 删除权限(目前没有判断父节点自动删除子节点)
|
|
||||||
power = RightModel.query.filter_by(id=_id).first()
|
|
||||||
role_id_list = []
|
|
||||||
roles = power.role
|
|
||||||
for role in roles:
|
|
||||||
role_id_list.append(role.id)
|
|
||||||
roles = RoleModel.query.filter(RoleModel.id.in_(role_id_list)).all()
|
|
||||||
for p in roles:
|
|
||||||
power.role.remove(p)
|
|
||||||
r = RightModel.query.filter_by(id=_id).delete()
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
if r:
|
|
||||||
return success_api(message="删除成功")
|
|
||||||
else:
|
|
||||||
return fail_api(message="删除失败")
|
|
||||||
|
|
||||||
@validate()
|
|
||||||
def put(self, _id, body: PowerModel):
|
|
||||||
data = {
|
|
||||||
"icon": body.icon,
|
|
||||||
"open_type": body.open_type,
|
|
||||||
"parent_id": body.parent_id,
|
|
||||||
"code": body.power_code,
|
|
||||||
"name": body.power_name,
|
|
||||||
"type": body.power_type,
|
|
||||||
"url": body.power_url,
|
|
||||||
"sort": body.sort
|
|
||||||
}
|
|
||||||
power = RightModel.query.filter_by(id=_id).update(data)
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
if not power:
|
|
||||||
return fail_api(message="更新权限失败")
|
|
||||||
return success_api(message="更新权限成功")
|
|
||||||
|
|
||||||
|
|
||||||
def right_power_enable_resource(_id, action):
|
|
||||||
power = RightModel.query.get(_id)
|
|
||||||
if power:
|
|
||||||
power.enable = not power.enable
|
|
||||||
db.session.commit()
|
|
||||||
message = "修改成功"
|
|
||||||
return success_api(message=message)
|
|
||||||
else:
|
|
||||||
return fail_api(message="出错啦")
|
|
||||||
|
|
||||||
|
|
||||||
def admin_configs_resource():
|
|
||||||
return get_render_config()
|
|
||||||
|
|
||||||
|
|
||||||
def admin_menu_resource():
|
|
||||||
menu_tree = make_menu_tree()
|
|
||||||
return jsonify(menu_tree)
|
|
||||||
@@ -1,162 +0,0 @@
|
|||||||
from flask import request
|
|
||||||
from flask.views import MethodView
|
|
||||||
|
|
||||||
from common.utils.http import table_api, success_api, fail_api
|
|
||||||
from extensions import db
|
|
||||||
from models import RightModel, RoleModel
|
|
||||||
|
|
||||||
|
|
||||||
def role_deletes():
|
|
||||||
ids = request.form.getlist('ids[]')
|
|
||||||
for id in ids:
|
|
||||||
role = RoleModel.query.filter_by(id=id).first()
|
|
||||||
# 删除该角色的权限和用户
|
|
||||||
role.power = []
|
|
||||||
role.user = []
|
|
||||||
|
|
||||||
r = RoleModel.query.filter_by(id=id).delete()
|
|
||||||
db.session.commit()
|
|
||||||
return success_api(message="批量删除成功")
|
|
||||||
|
|
||||||
|
|
||||||
class RoleRoleApi(MethodView):
|
|
||||||
|
|
||||||
def get(self, _id):
|
|
||||||
if not _id:
|
|
||||||
page = request.args.get('page', default=1, type=int)
|
|
||||||
limit = request.args.get('limit', default=10, type=int)
|
|
||||||
role_name = request.args.get('roleName', default="", type=str)
|
|
||||||
role_code = request.args.get('roleCode', default="", type=str)
|
|
||||||
|
|
||||||
filters = []
|
|
||||||
if role_name:
|
|
||||||
filters.append(RoleModel.name.like('%' + role_name + '%'))
|
|
||||||
if role_code:
|
|
||||||
filters.append(RoleModel.code.like('%' + role_code + '%'))
|
|
||||||
|
|
||||||
paginate = RoleModel.query.filter(*filters).paginate(page=page, per_page=limit, error_out=False)
|
|
||||||
|
|
||||||
return table_api(
|
|
||||||
result={
|
|
||||||
'items': [{'id': item.id,
|
|
||||||
'roleName': item.name,
|
|
||||||
'roleCode': item.code,
|
|
||||||
'enable': item.enable,
|
|
||||||
'comment': item.comment,
|
|
||||||
'details': item.details,
|
|
||||||
'sort': item.sort,
|
|
||||||
} for item in paginate.items],
|
|
||||||
'total': paginate.total}
|
|
||||||
, code=0)
|
|
||||||
|
|
||||||
def post(self):
|
|
||||||
# TODO 添加校验
|
|
||||||
details = request.json.get('details', '')
|
|
||||||
enable = request.json.get('enable', 0)
|
|
||||||
role_code = request.json.get('roleCode', '')
|
|
||||||
role_name = request.json.get('roleName', '')
|
|
||||||
sort = request.json.get('sort', 0)
|
|
||||||
|
|
||||||
role = RoleModel(
|
|
||||||
details=details,
|
|
||||||
enable=int(enable),
|
|
||||||
code=role_code,
|
|
||||||
name=role_name,
|
|
||||||
sort=int(sort)
|
|
||||||
)
|
|
||||||
db.session.add(role)
|
|
||||||
db.session.commit()
|
|
||||||
return success_api(message="成功")
|
|
||||||
|
|
||||||
# 更新角色
|
|
||||||
def put(self, _id):
|
|
||||||
# TODO 添加校验
|
|
||||||
role_code = request.json.get('roleCode', 0)
|
|
||||||
role_name = request.json.get('roleName', '')
|
|
||||||
sort = request.json.get('sort', 0) # int
|
|
||||||
enable = request.json.get('enable', 0) # int
|
|
||||||
details = request.json.get('details', '')
|
|
||||||
|
|
||||||
data = {
|
|
||||||
"code": role_code,
|
|
||||||
"name": role_name,
|
|
||||||
"sort": sort,
|
|
||||||
"enable": enable,
|
|
||||||
"details": details
|
|
||||||
}
|
|
||||||
|
|
||||||
role = RoleModel.query.filter_by(id=_id).update(data)
|
|
||||||
db.session.commit()
|
|
||||||
if not role:
|
|
||||||
return fail_api(message="更新角色失败")
|
|
||||||
return success_api(message="更新角色成功")
|
|
||||||
|
|
||||||
|
|
||||||
def role_enable_resource(_id):
|
|
||||||
"""启用用户"""
|
|
||||||
ret = RoleModel.query.get(_id)
|
|
||||||
ret.enable = not ret.enable
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
message = "修改成功"
|
|
||||||
if not ret:
|
|
||||||
return fail_api(message="出错啦")
|
|
||||||
return success_api(message=message)
|
|
||||||
|
|
||||||
|
|
||||||
class RolePowerApi(MethodView):
|
|
||||||
|
|
||||||
def get(self, _id):
|
|
||||||
# 获取角色权限
|
|
||||||
role = RoleModel.query.filter_by(id=_id).first()
|
|
||||||
# 获取权限列表的 id
|
|
||||||
check_powers_list = [rp.id for rp in role.power]
|
|
||||||
powers = RightModel.query.all() # 获取所有的权限
|
|
||||||
powers = [
|
|
||||||
{
|
|
||||||
'powerId': item.id,
|
|
||||||
'powerName': item.name,
|
|
||||||
'powerType': item.type,
|
|
||||||
'powerUrl': item.url,
|
|
||||||
'openType': item.open_type,
|
|
||||||
'parentId': item.parent_id,
|
|
||||||
'icon': item.icon,
|
|
||||||
'sort': item.sort,
|
|
||||||
'enable': item.enable,
|
|
||||||
} for item in powers]
|
|
||||||
for i in powers:
|
|
||||||
if int(i.get("powerId")) in check_powers_list:
|
|
||||||
i["checkArr"] = "1"
|
|
||||||
else:
|
|
||||||
i["checkArr"] = "0"
|
|
||||||
return {
|
|
||||||
"data": powers,
|
|
||||||
"status": {"code": 200, "message": "默认"}
|
|
||||||
}
|
|
||||||
|
|
||||||
# 保存角色权限
|
|
||||||
def put(self, _id):
|
|
||||||
power_ids = request.json.get('powerIds', '')
|
|
||||||
|
|
||||||
power_list = power_ids.split(',')
|
|
||||||
|
|
||||||
""" 更新角色权限 """
|
|
||||||
role = RoleModel.query.filter_by(id=_id).first()
|
|
||||||
powers = RightModel.query.filter(RightModel.id.in_(power_list)).all()
|
|
||||||
role.power = powers
|
|
||||||
|
|
||||||
db.session.commit()
|
|
||||||
return success_api(message="授权成功")
|
|
||||||
|
|
||||||
# 角色删除
|
|
||||||
def delete(self, _id):
|
|
||||||
role = RoleModel.query.filter_by(id=_id).first()
|
|
||||||
# 删除该角色的权限和用户
|
|
||||||
role.power = []
|
|
||||||
role.user = []
|
|
||||||
|
|
||||||
r = RoleModel.query.filter_by(id=_id).delete()
|
|
||||||
db.session.commit()
|
|
||||||
if not r:
|
|
||||||
return fail_api(message="角色删除失败")
|
|
||||||
return success_api(message="角色删除成功")
|
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
from .admin_user import UserOutSchema
|
||||||
|
from .admin_role import RoleOutSchema
|
||||||
|
from .admin_power import PowerOutSchema, PowerOutSchema2
|
||||||
|
from .admin_dict import DictDataOutSchema, DictTypeOutSchema
|
||||||
|
from .admin_dept import DeptOutSchema
|
||||||
|
from .admin_log import LogOutSchema
|
||||||
|
from .admin_photo import PhotoOutSchema
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
from applications.extensions import ma
|
||||||
|
from marshmallow import fields, validate
|
||||||
|
|
||||||
|
|
||||||
|
class DeptInSchema(ma.Schema):
|
||||||
|
parentId = fields.Integer(required=True)
|
||||||
|
deptName = fields.Str(required=True)
|
||||||
|
leader = fields.Str(required=True)
|
||||||
|
phone = fields.Str(required=True)
|
||||||
|
email = fields.Str(validate=validate.Email())
|
||||||
|
address = fields.Str()
|
||||||
|
status = fields.Str(validate=validate.OneOf(["0", "1"]))
|
||||||
|
sort = fields.Integer()
|
||||||
|
|
||||||
|
|
||||||
|
class DeptOutSchema(ma.Schema):
|
||||||
|
deptId = fields.Integer(attribute="id")
|
||||||
|
parentId = fields.Integer(attribute="parent_id")
|
||||||
|
deptName = fields.Str(attribute="dept_name")
|
||||||
|
leader = fields.Str()
|
||||||
|
phone = fields.Str()
|
||||||
|
email = fields.Str(validate=validate.Email())
|
||||||
|
address = fields.Str()
|
||||||
|
status = fields.Str(validate=validate.OneOf(["0", "1"]))
|
||||||
|
sort = fields.Integer()
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
from applications.extensions import ma
|
||||||
|
from marshmallow import fields
|
||||||
|
|
||||||
|
|
||||||
|
class DictTypeOutSchema(ma.Schema):
|
||||||
|
id = fields.Str(attribute="id")
|
||||||
|
typeName = fields.Str(attribute="type_name")
|
||||||
|
typeCode = fields.Str(attribute="type_code")
|
||||||
|
description = fields.Str(attribute="description")
|
||||||
|
createTime = fields.Str(attribute="create_time")
|
||||||
|
updateName = fields.Str(attribute="update_time")
|
||||||
|
remark = fields.Str()
|
||||||
|
enable = fields.Str()
|
||||||
|
|
||||||
|
|
||||||
|
class DictDataOutSchema(ma.Schema):
|
||||||
|
dataId = fields.Str(attribute="id")
|
||||||
|
dataLabel = fields.Str(attribute="data_label")
|
||||||
|
dataValue = fields.Str(attribute="data_value")
|
||||||
|
remark = fields.Str()
|
||||||
|
enable = fields.Str()
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
from applications.extensions import ma
|
||||||
|
from marshmallow import fields
|
||||||
|
|
||||||
|
|
||||||
|
class LogOutSchema(ma.Schema):
|
||||||
|
id = fields.Integer()
|
||||||
|
method = fields.Str()
|
||||||
|
uid = fields.Str()
|
||||||
|
url = fields.Str()
|
||||||
|
desc = fields.Str()
|
||||||
|
ip = fields.Str()
|
||||||
|
user_agent = fields.Str()
|
||||||
|
success = fields.Bool()
|
||||||
|
create_time = fields.DateTime()
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
from applications.extensions import ma
|
||||||
|
from marshmallow import fields
|
||||||
|
|
||||||
|
|
||||||
|
class PhotoOutSchema(ma.Schema):
|
||||||
|
id = fields.Integer()
|
||||||
|
name = fields.Str()
|
||||||
|
href = fields.Str()
|
||||||
|
mime = fields.Str()
|
||||||
|
size = fields.Str()
|
||||||
|
ext = fields.Str()
|
||||||
|
create_time = fields.DateTime()
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
from applications.extensions import ma
|
||||||
|
from marshmallow import fields
|
||||||
|
|
||||||
|
|
||||||
|
# 权限models序列化类
|
||||||
|
class PowerOutSchema(ma.Schema):
|
||||||
|
id = fields.Integer()
|
||||||
|
title = fields.Str(attribute="name")
|
||||||
|
type = fields.Str()
|
||||||
|
code = fields.Str()
|
||||||
|
href = fields.Str(attribute="url")
|
||||||
|
openType = fields.Str(attribute="open_type")
|
||||||
|
parent_id = fields.Integer()
|
||||||
|
icon = fields.Str()
|
||||||
|
sort = fields.Integer()
|
||||||
|
create_time = fields.DateTime()
|
||||||
|
update_time = fields.DateTime()
|
||||||
|
enable = fields.Integer()
|
||||||
|
|
||||||
|
|
||||||
|
class PowerOutSchema2(ma.Schema): # 序列化类
|
||||||
|
powerId = fields.Str(attribute="id")
|
||||||
|
powerName = fields.Str(attribute="name")
|
||||||
|
powerType = fields.Str(attribute="type")
|
||||||
|
powerUrl = fields.Str(attribute="url")
|
||||||
|
openType = fields.Str(attribute="open_type")
|
||||||
|
parentId = fields.Str(attribute="parent_id")
|
||||||
|
icon = fields.Str()
|
||||||
|
sort = fields.Integer()
|
||||||
|
create_time = fields.DateTime()
|
||||||
|
update_time = fields.DateTime()
|
||||||
|
enable = fields.Integer()
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
from applications.extensions import ma
|
||||||
|
from marshmallow import fields
|
||||||
|
|
||||||
|
|
||||||
|
class RoleOutSchema(ma.Schema):
|
||||||
|
id = fields.Integer()
|
||||||
|
roleName = fields.Str(attribute="name")
|
||||||
|
roleCode = fields.Str(attribute="code")
|
||||||
|
enable = fields.Str()
|
||||||
|
remark = fields.Str()
|
||||||
|
details = fields.Str()
|
||||||
|
sort = fields.Integer()
|
||||||
|
create_at = fields.DateTime()
|
||||||
|
update_at = fields.DateTime()
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
from applications.extensions import ma
|
||||||
|
from marshmallow import fields
|
||||||
|
from applications.models import Dept
|
||||||
|
|
||||||
|
|
||||||
|
# 用户models的序列化类
|
||||||
|
class UserOutSchema(ma.Schema):
|
||||||
|
id = fields.Integer()
|
||||||
|
username = fields.Str()
|
||||||
|
realname = fields.Str()
|
||||||
|
enable = fields.Integer()
|
||||||
|
create_at = fields.DateTime()
|
||||||
|
update_at = fields.DateTime()
|
||||||
|
dept = fields.Method("get_dept")
|
||||||
|
|
||||||
|
def get_dept(self, obj):
|
||||||
|
if obj.dept_id != None:
|
||||||
|
return Dept.query.filter_by(id=obj.dept_id).first().dept_name
|
||||||
|
else:
|
||||||
|
return None
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
from flask import Blueprint
|
|
||||||
|
|
||||||
from common import register_api
|
|
||||||
from .file import FilePhotoAPI
|
|
||||||
from .passport import LoginAPI
|
|
||||||
|
|
||||||
|
|
||||||
def register_sys_api(api_bp):
|
|
||||||
register_api(LoginAPI, 'login_api', '/passport/login', pk='_id', app=api_bp)
|
|
||||||
register_api(FilePhotoAPI, 'photo_api', '/file/photo/', pk='photo_id', app=api_bp)
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
from flask import request, jsonify
|
|
||||||
from flask.views import MethodView
|
|
||||||
from sqlalchemy import desc
|
|
||||||
|
|
||||||
from common.utils.http import fail_api, success_api, table_api
|
|
||||||
from common.utils.upload import upload_one, delete_photo_by_id
|
|
||||||
from models import PhotoModel
|
|
||||||
|
|
||||||
|
|
||||||
class FilePhotoAPI(MethodView):
|
|
||||||
|
|
||||||
def get(self, photo_id):
|
|
||||||
if photo_id is None:
|
|
||||||
page = request.args.get('page', type=int, default=1)
|
|
||||||
limit = request.args.get('limit', type=int, default=10)
|
|
||||||
photo_paginate = PhotoModel.query.order_by(
|
|
||||||
desc(PhotoModel.create_at)).paginate(
|
|
||||||
page=page, per_page=limit, error_out=False)
|
|
||||||
data = [
|
|
||||||
{
|
|
||||||
'id': item.id,
|
|
||||||
'name': item.name,
|
|
||||||
'href': item.href,
|
|
||||||
'mime': item.mime,
|
|
||||||
'size': item.size,
|
|
||||||
'ext': item.ext if hasattr(item, 'ext') else "",
|
|
||||||
'create_at': str(item.create_at),
|
|
||||||
} for item in photo_paginate.items
|
|
||||||
]
|
|
||||||
return table_api(
|
|
||||||
result={
|
|
||||||
'items': data,
|
|
||||||
'total': photo_paginate.total,
|
|
||||||
},
|
|
||||||
code=0)
|
|
||||||
else:
|
|
||||||
# 显示一张图片
|
|
||||||
item = PhotoModel.query.get(photo_id)
|
|
||||||
return table_api(
|
|
||||||
result={
|
|
||||||
'items': {
|
|
||||||
'id': item.id,
|
|
||||||
'name': item.name,
|
|
||||||
'href': item.href,
|
|
||||||
'mime': item.mime,
|
|
||||||
'size': item.size,
|
|
||||||
'ext': item.ext if hasattr(item, 'ext') else "",
|
|
||||||
'create_at': str(item.create_at),
|
|
||||||
},
|
|
||||||
'total': 1,
|
|
||||||
},
|
|
||||||
code=0
|
|
||||||
)
|
|
||||||
|
|
||||||
def post(self):
|
|
||||||
if 'file' in request.files:
|
|
||||||
photo = request.files['file']
|
|
||||||
mime = request.files['file'].content_type
|
|
||||||
file_url = upload_one(photo=photo, mime=mime)
|
|
||||||
|
|
||||||
res = {
|
|
||||||
"message": "上传成功",
|
|
||||||
"code": 0,
|
|
||||||
"success": True,
|
|
||||||
"data": {"src": file_url},
|
|
||||||
}
|
|
||||||
return jsonify(res)
|
|
||||||
return fail_api()
|
|
||||||
|
|
||||||
def delete(self, photo_id):
|
|
||||||
res = delete_photo_by_id(photo_id)
|
|
||||||
if res:
|
|
||||||
return success_api(message="删除成功")
|
|
||||||
else:
|
|
||||||
return fail_api(message="删除失败")
|
|
||||||
|
|
||||||
def put(self, photo_id):
|
|
||||||
pass
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
from flask import render_template, make_response
|
|
||||||
from flask import session, redirect, url_for
|
|
||||||
from flask.views import MethodView
|
|
||||||
from flask_login import current_user, login_user
|
|
||||||
from flask_pydantic import validate
|
|
||||||
from pydantic import BaseModel
|
|
||||||
|
|
||||||
from common.gen_captcha import add_auth_session
|
|
||||||
from common.utils.http import fail_api, success_api
|
|
||||||
from common.utils.rights import record_logging
|
|
||||||
from models import UserModel
|
|
||||||
|
|
||||||
|
|
||||||
class LoginModel(BaseModel):
|
|
||||||
username: str
|
|
||||||
password: str
|
|
||||||
captcha: str
|
|
||||||
|
|
||||||
|
|
||||||
class LoginAPI(MethodView):
|
|
||||||
|
|
||||||
def get(self):
|
|
||||||
if current_user.is_authenticated:
|
|
||||||
return redirect(url_for('admin.index'))
|
|
||||||
return make_response(render_template('index/login.html'))
|
|
||||||
|
|
||||||
@validate()
|
|
||||||
def post(self, body: LoginModel):
|
|
||||||
s_code = session.get("code", None)
|
|
||||||
session["code"] = None
|
|
||||||
|
|
||||||
if body.captcha != s_code:
|
|
||||||
return fail_api(message="验证码错误")
|
|
||||||
user = UserModel.query.filter_by(username=body.username).first()
|
|
||||||
|
|
||||||
if user is None:
|
|
||||||
return fail_api(message="不存在的用户")
|
|
||||||
|
|
||||||
if user.enable == 0:
|
|
||||||
return fail_api(message="用户被暂停使用")
|
|
||||||
|
|
||||||
if user.validate_password(body.password):
|
|
||||||
# 登录
|
|
||||||
login_user(user)
|
|
||||||
# 记录登录日志
|
|
||||||
record_logging()
|
|
||||||
|
|
||||||
# 存入权限
|
|
||||||
add_auth_session()
|
|
||||||
return success_api(message="登录成功")
|
|
||||||
record_logging()
|
|
||||||
return fail_api(message="用户名或密码错误")
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
from common import register_api
|
|
||||||
from .user import UserApi, user_role_resource, user_info
|
|
||||||
|
|
||||||
|
|
||||||
def register_users_api(api_bp):
|
|
||||||
api_bp.add_url_rule('/users/user/<int:_id>/<action>',
|
|
||||||
view_func=user_info,
|
|
||||||
methods=['PUT'])
|
|
||||||
|
|
||||||
register_api(UserApi, 'users_api', '/users/user/', pk='_id', app=api_bp)
|
|
||||||
|
|
||||||
api_bp.add_url_rule('/users/user/<int:_id>/role',
|
|
||||||
view_func=user_role_resource,
|
|
||||||
methods=['PUT'])
|
|
||||||
@@ -1,243 +0,0 @@
|
|||||||
import typing as t
|
|
||||||
|
|
||||||
from flask import request, jsonify
|
|
||||||
from flask.views import MethodView
|
|
||||||
from flask_login import current_user
|
|
||||||
from flask_pydantic import validate
|
|
||||||
from pydantic import BaseModel, Field
|
|
||||||
from sqlalchemy import desc
|
|
||||||
|
|
||||||
from common.utils.http import fail_api, success_api, table_api
|
|
||||||
from extensions import db
|
|
||||||
from models import LogModel
|
|
||||||
from models import UserModel, RoleModel, DepartmentModel
|
|
||||||
|
|
||||||
|
|
||||||
def get_current_user_logs():
|
|
||||||
""" 获取当前用户日志 """
|
|
||||||
log = LogModel.query.filter_by(url='/passport/login').filter_by(uid=current_user.id).order_by(
|
|
||||||
desc(LogModel.create_at)).limit(10)
|
|
||||||
return log
|
|
||||||
|
|
||||||
|
|
||||||
def is_user_exists(username):
|
|
||||||
""" 判断用户是否存在 """
|
|
||||||
res = UserModel.query.filter_by(username=username).count()
|
|
||||||
return bool(res)
|
|
||||||
|
|
||||||
|
|
||||||
def delete_by_id(_id):
|
|
||||||
""" 删除用户 """
|
|
||||||
user = UserModel.query.filter_by(id=_id).first()
|
|
||||||
roles_id = []
|
|
||||||
for role in user.role:
|
|
||||||
roles_id.append(role.id)
|
|
||||||
roles = RoleModel.query.filter(RoleModel.id.in_(roles_id)).all()
|
|
||||||
for r in roles:
|
|
||||||
user.role.remove(r)
|
|
||||||
res = UserModel.query.filter_by(id=_id).delete()
|
|
||||||
db.session.commit()
|
|
||||||
return res
|
|
||||||
|
|
||||||
|
|
||||||
def batch_remove(ids):
|
|
||||||
""" 批量删除 """
|
|
||||||
for _id in ids:
|
|
||||||
delete_by_id(_id)
|
|
||||||
|
|
||||||
|
|
||||||
def update_user_role(_id, roles_list):
|
|
||||||
user = UserModel.query.filter_by(id=_id).first()
|
|
||||||
roles_id = []
|
|
||||||
for role in user.role:
|
|
||||||
roles_id.append(role.id)
|
|
||||||
roles = RoleModel.query.filter(RoleModel.id.in_(roles_id)).all()
|
|
||||||
for r in roles:
|
|
||||||
user.role.remove(r)
|
|
||||||
roles = RoleModel.query.filter(RoleModel.id.in_(roles_list)).all()
|
|
||||||
for r in roles:
|
|
||||||
user.role.append(r)
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
|
|
||||||
def users_delete():
|
|
||||||
"""批量删除"""
|
|
||||||
ids = request.form.getlist('ids[]')
|
|
||||||
batch_remove(ids)
|
|
||||||
return success_api(message="批量删除成功")
|
|
||||||
|
|
||||||
|
|
||||||
class QueryModel(BaseModel):
|
|
||||||
page: int = 1
|
|
||||||
limit: int = 10
|
|
||||||
real_name: t.Optional[str] = Field(alias='realName')
|
|
||||||
username: t.Optional[str]
|
|
||||||
dept_id: t.Optional[str] = Field(alias='deptId', default=0)
|
|
||||||
phone: t.Optional[str]
|
|
||||||
sort: t.Optional[int]
|
|
||||||
status: t.Optional[int]
|
|
||||||
|
|
||||||
|
|
||||||
class PersonModel(BaseModel):
|
|
||||||
role_ids: str = Field(alias='roleIds')
|
|
||||||
username: str
|
|
||||||
real_name: str = Field(alias='realName')
|
|
||||||
password: str
|
|
||||||
|
|
||||||
|
|
||||||
class UserApi(MethodView):
|
|
||||||
"""修改用户数据"""
|
|
||||||
|
|
||||||
@validate()
|
|
||||||
def get(self, _id, query: QueryModel):
|
|
||||||
|
|
||||||
filters = []
|
|
||||||
|
|
||||||
if query.real_name:
|
|
||||||
filters.append(UserModel.realname.like('%' + query.real_name + '%'))
|
|
||||||
if query.username:
|
|
||||||
filters.append(UserModel.username.like('%' + query.username + '%'))
|
|
||||||
if query.dept_id:
|
|
||||||
filters.append(UserModel.dept_id == query.dept_id)
|
|
||||||
|
|
||||||
paginate = UserModel.query.filter(
|
|
||||||
*filters).paginate(
|
|
||||||
page=query.page, per_page=query.limit, error_out=False)
|
|
||||||
|
|
||||||
dept_name = lambda _id: DepartmentModel.query.filter_by(id=_id).first().dept_name if _id else ""
|
|
||||||
user_data = [{
|
|
||||||
'id': item.id,
|
|
||||||
'username': item.username,
|
|
||||||
'realname': item.realname,
|
|
||||||
'enable': item.enable,
|
|
||||||
'create_at': str(item.create_at),
|
|
||||||
'update_at': str(item.update_at),
|
|
||||||
'dept': dept_name(item.dept_id),
|
|
||||||
} for item in paginate.items]
|
|
||||||
return table_api(
|
|
||||||
result={
|
|
||||||
'items': user_data,
|
|
||||||
'total': paginate.total,
|
|
||||||
}
|
|
||||||
, code=0
|
|
||||||
)
|
|
||||||
|
|
||||||
@validate()
|
|
||||||
def post(self, body: PersonModel):
|
|
||||||
"""新建单个用户"""
|
|
||||||
|
|
||||||
role_ids = body.role_ids.split(',')
|
|
||||||
|
|
||||||
if is_user_exists(body.username):
|
|
||||||
return fail_api(message="用户已经存在")
|
|
||||||
|
|
||||||
user = UserModel()
|
|
||||||
user.username = body.username
|
|
||||||
user.realname = body.real_name
|
|
||||||
user.set_password(body.password)
|
|
||||||
db.session.add(user)
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
""" 增加用户角色 """
|
|
||||||
user = UserModel.query.filter_by(id=user.id).first()
|
|
||||||
roles = RoleModel.query.filter(RoleModel.id.in_(role_ids)).all()
|
|
||||||
for r in roles:
|
|
||||||
user.role.append(r)
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
return success_api(message="增加成功", code=0)
|
|
||||||
|
|
||||||
def delete(self, _id):
|
|
||||||
# 删除用户
|
|
||||||
res = delete_by_id(_id)
|
|
||||||
if not res:
|
|
||||||
return fail_api(message="删除失败")
|
|
||||||
return success_api(message="删除成功")
|
|
||||||
|
|
||||||
|
|
||||||
class PersonModel2(BaseModel):
|
|
||||||
role_ids: str = Field(alias='roleIds')
|
|
||||||
user_id: str = Field(alias='userId')
|
|
||||||
username: str
|
|
||||||
real_name: str = Field(alias='realName')
|
|
||||||
dept_id: str = Field(alias='deptId')
|
|
||||||
|
|
||||||
|
|
||||||
@validate()
|
|
||||||
def user_role_resource(_id, body: PersonModel2):
|
|
||||||
role_ids = body.role_ids.split(',')
|
|
||||||
|
|
||||||
# 更新用户数据
|
|
||||||
UserModel.query.filter_by(id=_id).update({'username': body.username,
|
|
||||||
'realname': body.real_name,
|
|
||||||
'dept_id': body.dept_id})
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
update_user_role(_id, role_ids)
|
|
||||||
|
|
||||||
return success_api(message="更新成功")
|
|
||||||
|
|
||||||
|
|
||||||
def user_info(_id, action):
|
|
||||||
if action == 'info':
|
|
||||||
real_name = request.json.get('realName', '')
|
|
||||||
username = request.json.get('username', '')
|
|
||||||
remark = request.json.get('remark', '')
|
|
||||||
details = request.json.get('details', '')
|
|
||||||
|
|
||||||
ret = UserModel.query.get(_id)
|
|
||||||
ret.username = username
|
|
||||||
ret.realname = real_name
|
|
||||||
ret.remark = details
|
|
||||||
db.session.commit()
|
|
||||||
if not ret:
|
|
||||||
return fail_api(message="出错啦")
|
|
||||||
return success_api(message="更新成功")
|
|
||||||
elif action == 'status':
|
|
||||||
user_id = int(request.json.get('userId', 0)) # int
|
|
||||||
operate = int(request.json.get('operate', 0)) # int
|
|
||||||
if operate not in [0, 1]:
|
|
||||||
return {'status': 'error', 'message': '请求有误'}
|
|
||||||
|
|
||||||
if operate == 1:
|
|
||||||
user = UserModel.query.get(_id)
|
|
||||||
user.enable = operate
|
|
||||||
message = success_api(message="启动成功")
|
|
||||||
else:
|
|
||||||
user = UserModel.query.filter_by(id=user_id).update({"enable": operate})
|
|
||||||
message = success_api(message="禁用成功")
|
|
||||||
if user:
|
|
||||||
db.session.commit()
|
|
||||||
else:
|
|
||||||
return fail_api(message="出错啦")
|
|
||||||
return message
|
|
||||||
elif action == 'avatar':
|
|
||||||
url = request.json.get("avatar").get("src")
|
|
||||||
ret = UserModel.query.get(_id)
|
|
||||||
ret.avatar = url
|
|
||||||
db.session.commit()
|
|
||||||
if not ret:
|
|
||||||
return fail_api(message="出错啦")
|
|
||||||
return success_api(message="修改成功")
|
|
||||||
elif action == 'password':
|
|
||||||
oldPassword = request.json.get('oldPassword', '')
|
|
||||||
newPassword = request.json.get('newPassword', '')
|
|
||||||
confirmPassword = request.json.get('confirmPassword', '')
|
|
||||||
if not all([oldPassword, newPassword, confirmPassword]):
|
|
||||||
return {'status': 'error', 'message': '密码不能为空'}
|
|
||||||
|
|
||||||
if newPassword != confirmPassword:
|
|
||||||
return fail_api(message='确认密码不一致')
|
|
||||||
|
|
||||||
""" 修改当前用户密码 """
|
|
||||||
user = UserModel.query.get(_id)
|
|
||||||
is_right = user.validate_password(oldPassword)
|
|
||||||
if not is_right:
|
|
||||||
return jsonify(success=False, message="旧密码错误")
|
|
||||||
user.set_password(newPassword)
|
|
||||||
db.session.add(user)
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
return jsonify(success=True, message="更改成功")
|
|
||||||
else:
|
|
||||||
return jsonify(success=False, message="操作有误")
|
|
||||||
@@ -1,17 +1,13 @@
|
|||||||
from flask import Flask
|
from applications.view.admin import register_admin_views
|
||||||
|
from applications.view.index import register_index_views
|
||||||
from .index import index_bp
|
from applications.view.passport import register_passport_views
|
||||||
from .logs_view import logs_bp
|
from applications.view.rights import register_rights_view
|
||||||
from .roles import role_bp
|
from applications.view.department import register_dept_views
|
||||||
|
|
||||||
from . import department
|
|
||||||
from . import file
|
|
||||||
from . import rights
|
|
||||||
from . import passport
|
|
||||||
from . import users
|
|
||||||
|
|
||||||
|
|
||||||
def init_view(app: Flask):
|
def init_view(app):
|
||||||
app.register_blueprint(index_bp)
|
register_admin_views(app)
|
||||||
app.register_blueprint(logs_bp)
|
register_index_views(app)
|
||||||
app.register_blueprint(role_bp)
|
register_rights_view(app)
|
||||||
|
register_passport_views(app)
|
||||||
|
register_dept_views(app)
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
from applications.view.admin.admin_log import admin_log
|
||||||
|
from applications.view.admin.dict import admin_dict
|
||||||
|
from applications.view.admin.index import admin_bp
|
||||||
|
from applications.view.admin.file import admin_file
|
||||||
|
from applications.view.admin.power import admin_power
|
||||||
|
from applications.view.admin.role import admin_role
|
||||||
|
from applications.view.admin.user import admin_user
|
||||||
|
from applications.view.admin.monitor import admin_monitor_bp
|
||||||
|
from applications.view.admin.task import admin_task
|
||||||
|
|
||||||
|
|
||||||
|
def register_admin_views(app: Flask):
|
||||||
|
app.register_blueprint(admin_bp)
|
||||||
|
app.register_blueprint(admin_user)
|
||||||
|
app.register_blueprint(admin_file)
|
||||||
|
app.register_blueprint(admin_monitor_bp)
|
||||||
|
app.register_blueprint(admin_log)
|
||||||
|
app.register_blueprint(admin_power)
|
||||||
|
app.register_blueprint(admin_role)
|
||||||
|
app.register_blueprint(admin_dict)
|
||||||
|
app.register_blueprint(admin_task)
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
from flask import Blueprint, request, render_template
|
||||||
|
from sqlalchemy import desc
|
||||||
|
from applications.common.utils.http import table_api
|
||||||
|
from applications.common.utils.rights import authorize
|
||||||
|
from applications.models import AdminLog
|
||||||
|
from applications.schemas import LogOutSchema
|
||||||
|
from applications.common.curd import model_to_dicts
|
||||||
|
|
||||||
|
admin_log = Blueprint('adminLog', __name__, url_prefix='/admin/log')
|
||||||
|
|
||||||
|
|
||||||
|
# 日志管理
|
||||||
|
@admin_log.get('/')
|
||||||
|
@authorize("admin:log:main")
|
||||||
|
def index():
|
||||||
|
return render_template('admin/admin_log/main.html')
|
||||||
|
|
||||||
|
|
||||||
|
# 登录日志
|
||||||
|
@admin_log.get('/loginLog')
|
||||||
|
@authorize("admin:log:main")
|
||||||
|
def login_log():
|
||||||
|
# orm查询
|
||||||
|
# 使用分页获取data需要.items
|
||||||
|
log = AdminLog.query.filter_by(url='/passport/login').order_by(desc(AdminLog.create_time)).layui_paginate()
|
||||||
|
count = log.total
|
||||||
|
return table_api(data= model_to_dicts(schema=LogOutSchema, data=log.items), count=count)
|
||||||
|
|
||||||
|
|
||||||
|
# 操作日志
|
||||||
|
@admin_log.get('/operateLog')
|
||||||
|
@authorize("admin:log:main")
|
||||||
|
def operate_log():
|
||||||
|
# orm查询
|
||||||
|
# 使用分页获取data需要.items
|
||||||
|
log = AdminLog.query.filter(
|
||||||
|
AdminLog.url != '/passport/login').order_by(
|
||||||
|
desc(AdminLog.create_time)).layui_paginate()
|
||||||
|
count = log.total
|
||||||
|
return table_api(data=model_to_dicts(schema=LogOutSchema, data=log.items), count=count)
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
from flask import Blueprint, render_template, request, jsonify
|
||||||
|
|
||||||
|
from applications.common import curd
|
||||||
|
from applications.common.helper import ModelFilter
|
||||||
|
from applications.common.utils.http import table_api, success_api, fail_api
|
||||||
|
from applications.common.utils.rights import authorize
|
||||||
|
from applications.common.utils.validate import xss_escape
|
||||||
|
from applications.extensions import db
|
||||||
|
from applications.models import DictType, DictData
|
||||||
|
from applications.schemas import DictTypeOutSchema, DictDataOutSchema
|
||||||
|
|
||||||
|
admin_dict = Blueprint('adminDict', __name__, url_prefix='/admin/dict')
|
||||||
|
|
||||||
|
|
||||||
|
# 数据字典
|
||||||
|
@admin_dict.get('/')
|
||||||
|
@authorize("admin:dict:main", log=True)
|
||||||
|
def main():
|
||||||
|
return render_template('admin/dict/main.html')
|
||||||
|
|
||||||
|
|
||||||
|
@admin_dict.get('/dictType/data')
|
||||||
|
@authorize("admin:dict:main", log=True)
|
||||||
|
def dict_type_data():
|
||||||
|
# 获取请求参数
|
||||||
|
type_name = xss_escape(request.args.get('typeName', type=str))
|
||||||
|
# 查询参数构造
|
||||||
|
mf = ModelFilter()
|
||||||
|
if type_name:
|
||||||
|
mf.vague(field_name="type_name", value=type_name)
|
||||||
|
# orm查询
|
||||||
|
# 使用分页获取data需要.items
|
||||||
|
dict_all = DictType.query.filter(mf.get_filter(DictType)).layui_paginate()
|
||||||
|
count = dict_all.total
|
||||||
|
data = curd.model_to_dicts(schema=DictTypeOutSchema, data=dict_all.items)
|
||||||
|
return table_api(data=data, count=count)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_dict.get('/dictType/add')
|
||||||
|
@authorize("admin:dict:add", log=True)
|
||||||
|
def dict_type_add():
|
||||||
|
return render_template('admin/dict/add.html')
|
||||||
|
|
||||||
|
|
||||||
|
@admin_dict.post('/dictType/save')
|
||||||
|
@authorize("admin:dict:add", log=True)
|
||||||
|
def dict_type_save():
|
||||||
|
req_json = request.json
|
||||||
|
description = xss_escape(req_json.get("description"))
|
||||||
|
enable = xss_escape(req_json.get("enable"))
|
||||||
|
type_code = xss_escape(req_json.get("typeCode"))
|
||||||
|
type_name = xss_escape(req_json.get("typeName"))
|
||||||
|
d = DictType(type_name=type_name, type_code=type_code, enable=enable, description=description)
|
||||||
|
db.session.add(d)
|
||||||
|
db.session.commit()
|
||||||
|
if d.id is None:
|
||||||
|
return fail_api(msg="增加失败")
|
||||||
|
return success_api(msg="增加成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 编辑字典类型
|
||||||
|
@admin_dict.get('/dictType/edit')
|
||||||
|
@authorize("admin:dict:edit", log=True)
|
||||||
|
def dict_type_edit():
|
||||||
|
_id = request.args.get('dictTypeId', type=int)
|
||||||
|
dict_type = DictType.query.filter_by(id=_id).first()
|
||||||
|
return render_template('admin/dict/edit.html', dict_type=dict_type)
|
||||||
|
|
||||||
|
|
||||||
|
# 编辑字典类型
|
||||||
|
@admin_dict.put('/dictType/update')
|
||||||
|
@authorize("admin:dict:edit", log=True)
|
||||||
|
def dict_type_update():
|
||||||
|
req_json = request.json
|
||||||
|
id = xss_escape(req_json.get("id"))
|
||||||
|
description = xss_escape(req_json.get("description"))
|
||||||
|
enable = xss_escape(req_json.get("enable"))
|
||||||
|
type_code = xss_escape(req_json.get("typeCode"))
|
||||||
|
type_name = xss_escape(req_json.get("typeName"))
|
||||||
|
DictType.query.filter_by(id=id).update({
|
||||||
|
"description": description,
|
||||||
|
"enable": enable,
|
||||||
|
"type_code": type_code,
|
||||||
|
"type_name": type_name
|
||||||
|
})
|
||||||
|
db.session.commit()
|
||||||
|
return success_api(msg="更新成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 启用字典
|
||||||
|
@admin_dict.put('/dictType/enable')
|
||||||
|
@authorize("admin:dict:edit", log=True)
|
||||||
|
def dict_type_enable():
|
||||||
|
_id = request.json.get('id')
|
||||||
|
if id:
|
||||||
|
res = curd.enable_status(DictType,_id)
|
||||||
|
if not res:
|
||||||
|
return fail_api(msg="出错啦")
|
||||||
|
return success_api("启动成功")
|
||||||
|
return fail_api(msg="数据错误")
|
||||||
|
|
||||||
|
|
||||||
|
# 禁用字典
|
||||||
|
@admin_dict.put('/dictType/disable')
|
||||||
|
@authorize("admin:dict:edit", log=True)
|
||||||
|
def dict_type_dis_enable():
|
||||||
|
_id = request.json.get('id')
|
||||||
|
if id:
|
||||||
|
res = curd.disable_status(DictType,_id)
|
||||||
|
if not res:
|
||||||
|
return fail_api(msg="出错啦")
|
||||||
|
return success_api("禁用成功")
|
||||||
|
return fail_api(msg="数据错误")
|
||||||
|
|
||||||
|
|
||||||
|
# 删除字典类型
|
||||||
|
@admin_dict.delete('/dictType/remove/<int:_id>')
|
||||||
|
@authorize("admin:dict:remove", log=True)
|
||||||
|
def dict_type_delete(_id):
|
||||||
|
res = curd.delete_one_by_id(DictType,_id)
|
||||||
|
if not res:
|
||||||
|
return fail_api(msg="删除失败")
|
||||||
|
return success_api(msg="删除成功")
|
||||||
|
|
||||||
|
|
||||||
|
@admin_dict.get('/dictData/data')
|
||||||
|
@authorize("admin:dict:main", log=True)
|
||||||
|
def dict_code_data():
|
||||||
|
type_code = xss_escape(request.args.get('typeCode', type=str))
|
||||||
|
dict_data = DictData.query.filter_by(type_code=type_code).layui_paginate()
|
||||||
|
count = dict_data.total
|
||||||
|
data = curd.model_to_dicts(schema=DictDataOutSchema, data=dict_data.items)
|
||||||
|
return table_api(data=data, count=count)
|
||||||
|
|
||||||
|
|
||||||
|
# 增加字典数据
|
||||||
|
@admin_dict.get('/dictData/add')
|
||||||
|
@authorize("admin:dict:add", log=True)
|
||||||
|
def dict_data_add():
|
||||||
|
type_code = request.args.get('typeCode', type=str)
|
||||||
|
return render_template('admin/dict/data/add.html', type_code=type_code)
|
||||||
|
|
||||||
|
|
||||||
|
# 增加字典数据
|
||||||
|
@admin_dict.post('/dictData/save')
|
||||||
|
@authorize("admin:dict:add", log=True)
|
||||||
|
def dict_data_save():
|
||||||
|
req_json = request.json
|
||||||
|
data_label = xss_escape(req_json.get("dataLabel"))
|
||||||
|
data_value = xss_escape(req_json.get("dataValue"))
|
||||||
|
enable = xss_escape(req_json.get("enable"))
|
||||||
|
remark = xss_escape(req_json.get("remark"))
|
||||||
|
type_code = xss_escape(req_json.get("typeCode"))
|
||||||
|
d = DictData(data_label=data_label, data_value=data_value, enable=enable, remark=remark, type_code=type_code)
|
||||||
|
db.session.add(d)
|
||||||
|
db.session.commit()
|
||||||
|
if not d.id:
|
||||||
|
return jsonify(success=False, msg="增加失败")
|
||||||
|
return jsonify(success=True, msg="增加成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 编辑字典数据
|
||||||
|
@admin_dict.get('/dictData/edit')
|
||||||
|
@authorize("admin:dict:edit", log=True)
|
||||||
|
def dict_data_edit():
|
||||||
|
_id = request.args.get('dataId', type=str)
|
||||||
|
dict_data = curd.get_one_by_id(DictData, _id)
|
||||||
|
return render_template('admin/dict/data/edit.html', dict_data=dict_data)
|
||||||
|
|
||||||
|
|
||||||
|
# 编辑字典数据
|
||||||
|
@admin_dict.put('/dictData/update')
|
||||||
|
@authorize("admin:dict:edit", log=True)
|
||||||
|
def dict_data_update():
|
||||||
|
req_json = request.json
|
||||||
|
id = req_json.get("dataId")
|
||||||
|
DictData.query.filter_by(id=id).update({
|
||||||
|
"data_label": xss_escape(req_json.get("dataLabel")),
|
||||||
|
"data_value": xss_escape(req_json.get("dataValue")),
|
||||||
|
"enable": xss_escape(req_json.get("enable")),
|
||||||
|
"remark": xss_escape(req_json.get("remark")),
|
||||||
|
"type_code": xss_escape(req_json.get("typeCode"))
|
||||||
|
})
|
||||||
|
db.session.commit()
|
||||||
|
return success_api(msg="更新成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 启用字典数据
|
||||||
|
@admin_dict.put('/dictData/enable')
|
||||||
|
@authorize("admin:dict:edit", log=True)
|
||||||
|
def dict_data_enable():
|
||||||
|
_id = request.json.get('dataId')
|
||||||
|
if _id:
|
||||||
|
res = curd.enable_status(model=DictData, id=_id)
|
||||||
|
if not res:
|
||||||
|
return fail_api(msg="出错啦")
|
||||||
|
return success_api(msg="启动成功")
|
||||||
|
return fail_api(msg="数据错误")
|
||||||
|
|
||||||
|
|
||||||
|
# 禁用字典数据
|
||||||
|
@admin_dict.put('/dictData/disable')
|
||||||
|
@authorize("admin:dict:edit", log=True)
|
||||||
|
def dict_data_disenable():
|
||||||
|
_id = request.json.get('dataId')
|
||||||
|
if _id:
|
||||||
|
res = curd.disable_status(model=DictData, id=_id)
|
||||||
|
if not res:
|
||||||
|
return fail_api(msg="出错啦")
|
||||||
|
return success_api(msg="禁用成功")
|
||||||
|
return fail_api(msg="数据错误")
|
||||||
|
|
||||||
|
|
||||||
|
# 删除字典类型
|
||||||
|
@admin_dict.delete('dictData/remove/<int:id>')
|
||||||
|
@authorize("admin:dict:remove", log=True)
|
||||||
|
def dict_data_delete(id):
|
||||||
|
res = curd.delete_one_by_id(model=DictData, id=id)
|
||||||
|
if not res:
|
||||||
|
return fail_api(msg="删除失败")
|
||||||
|
return success_api(msg="删除成功")
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import os
|
||||||
|
from flask import Blueprint, request, render_template, jsonify, current_app
|
||||||
|
|
||||||
|
from applications.common.utils.http import fail_api, success_api, table_api
|
||||||
|
from applications.common.utils.rights import authorize
|
||||||
|
from applications.extensions import db
|
||||||
|
from applications.models import Photo
|
||||||
|
from applications.common.utils import upload as upload_curd
|
||||||
|
|
||||||
|
admin_file = Blueprint('adminFile', __name__, url_prefix='/admin/file')
|
||||||
|
|
||||||
|
|
||||||
|
# 图片管理
|
||||||
|
@admin_file.get('/')
|
||||||
|
@authorize("admin:file:main", log=True)
|
||||||
|
def index():
|
||||||
|
return render_template('admin/photo/photo.html')
|
||||||
|
|
||||||
|
|
||||||
|
# 图片数据
|
||||||
|
@admin_file.get('/table')
|
||||||
|
@authorize("admin:file:main", log=True)
|
||||||
|
def table():
|
||||||
|
page = request.args.get('page', type=int)
|
||||||
|
limit = request.args.get('limit', type=int)
|
||||||
|
data, count = upload_curd.get_photo(page=page, limit=limit)
|
||||||
|
return table_api(data=data, count=count)
|
||||||
|
|
||||||
|
|
||||||
|
# 上传
|
||||||
|
@admin_file.get('/upload')
|
||||||
|
@authorize("admin:file:add", log=True)
|
||||||
|
def upload():
|
||||||
|
return render_template('admin/photo/photo_add.html')
|
||||||
|
|
||||||
|
|
||||||
|
# 上传接口
|
||||||
|
@admin_file.post('/upload')
|
||||||
|
@authorize("admin:file:add", log=True)
|
||||||
|
def upload_api():
|
||||||
|
if 'file' in request.files:
|
||||||
|
photo = request.files['file']
|
||||||
|
mime = request.files['file'].content_type
|
||||||
|
|
||||||
|
file_url = upload_curd.upload_one(photo=photo, mime=mime)
|
||||||
|
res = {
|
||||||
|
"msg": "上传成功",
|
||||||
|
"code": 0,
|
||||||
|
"success": True,
|
||||||
|
"data":
|
||||||
|
{"src": file_url}
|
||||||
|
}
|
||||||
|
return jsonify(res)
|
||||||
|
return fail_api()
|
||||||
|
|
||||||
|
|
||||||
|
# 图片删除
|
||||||
|
@admin_file.route('/delete', methods=['GET', 'POST'])
|
||||||
|
@authorize("admin:file:delete", log=True)
|
||||||
|
def delete():
|
||||||
|
_id = request.form.get('id')
|
||||||
|
res = upload_curd.delete_photo_by_id(_id)
|
||||||
|
if res:
|
||||||
|
return success_api(msg="删除成功")
|
||||||
|
else:
|
||||||
|
return fail_api(msg="删除失败")
|
||||||
|
|
||||||
|
|
||||||
|
# 图片批量删除
|
||||||
|
@admin_file.route('/batchRemove', methods=['GET', 'POST'])
|
||||||
|
@authorize("admin:file:delete", log=True)
|
||||||
|
def batch_remove():
|
||||||
|
ids = request.form.getlist('ids[]')
|
||||||
|
photo_name = Photo.query.filter(Photo.id.in_(ids)).all()
|
||||||
|
upload_url = current_app.config.get("UPLOADED_PHOTOS_DEST")
|
||||||
|
for p in photo_name:
|
||||||
|
os.remove(upload_url + '/' + p.name)
|
||||||
|
photo = Photo.query.filter(Photo.id.in_(ids)).delete(synchronize_session=False)
|
||||||
|
db.session.commit()
|
||||||
|
if photo:
|
||||||
|
return success_api(msg="删除成功")
|
||||||
|
else:
|
||||||
|
return fail_api(msg="删除失败")
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
from flask import Blueprint, render_template
|
||||||
|
from flask_login import login_required, current_user
|
||||||
|
|
||||||
|
admin_bp = Blueprint('admin', __name__, url_prefix='/admin')
|
||||||
|
|
||||||
|
|
||||||
|
# 首页
|
||||||
|
@admin_bp.get('/')
|
||||||
|
@login_required
|
||||||
|
def index():
|
||||||
|
user = current_user
|
||||||
|
return render_template('admin/index.html', user=user)
|
||||||
|
|
||||||
|
|
||||||
|
# 控制台页面
|
||||||
|
@admin_bp.get('/welcome')
|
||||||
|
@login_required
|
||||||
|
def welcome():
|
||||||
|
return render_template('admin/console/console.html')
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import os
|
||||||
|
import platform
|
||||||
|
import re
|
||||||
|
from datetime import datetime
|
||||||
|
import time
|
||||||
|
import psutil
|
||||||
|
from flask import Blueprint, render_template, jsonify
|
||||||
|
from applications.common.utils.rights import authorize
|
||||||
|
|
||||||
|
admin_monitor_bp = Blueprint('adminMonitor', __name__, url_prefix='/admin/monitor')
|
||||||
|
|
||||||
|
|
||||||
|
# 系统监控
|
||||||
|
@admin_monitor_bp.get('/')
|
||||||
|
@authorize("admin:monitor:main", log=True)
|
||||||
|
def main():
|
||||||
|
# 主机名称
|
||||||
|
hostname = platform.node()
|
||||||
|
# 系统版本
|
||||||
|
system_version = platform.platform()
|
||||||
|
# python版本
|
||||||
|
python_version = platform.python_version()
|
||||||
|
# 逻辑cpu数量
|
||||||
|
cpu_count = psutil.cpu_count()
|
||||||
|
# cup使用率
|
||||||
|
cpus_percent = psutil.cpu_percent(interval=0.1)
|
||||||
|
# 内存
|
||||||
|
memory_information = psutil.virtual_memory()
|
||||||
|
# 内存使用率
|
||||||
|
memory_usage = memory_information.percent
|
||||||
|
memory_used = str(round(memory_information.used / 1024 / 1024))
|
||||||
|
memory_total = str(round(memory_information.total / 1024 / 1024))
|
||||||
|
memory_free = str(round(memory_information.free / 1024 / 1024))
|
||||||
|
# 磁盘信息
|
||||||
|
|
||||||
|
disk_partitions_list = []
|
||||||
|
# 判断是否在容器中
|
||||||
|
if not os.path.exists('/.dockerenv'):
|
||||||
|
disk_partitions = psutil.disk_partitions()
|
||||||
|
for i in disk_partitions:
|
||||||
|
a = psutil.disk_usage(i.device)
|
||||||
|
disk_partitions_dict = {
|
||||||
|
'device': i.device,
|
||||||
|
'fstype': i.fstype,
|
||||||
|
'total': str(round(a.total / 1024 / 1024)),
|
||||||
|
'used': str(round(a.used / 1024 / 1024)),
|
||||||
|
'free': str(round(a.free / 1024 / 1024)),
|
||||||
|
'percent': a.percent
|
||||||
|
}
|
||||||
|
disk_partitions_list.append(disk_partitions_dict)
|
||||||
|
|
||||||
|
# 开机时间
|
||||||
|
boot_time = datetime.fromtimestamp(psutil.boot_time()).replace(microsecond=0)
|
||||||
|
up_time = datetime.now().replace(microsecond=0) - boot_time
|
||||||
|
up_time_list = re.split(r':', str(up_time))
|
||||||
|
up_time_format = " {} 小时{} 分钟{} 秒".format(up_time_list[0], up_time_list[1], up_time_list[2])
|
||||||
|
|
||||||
|
# 当前时间
|
||||||
|
time_now = time.strftime('%H:%M:%S ', time.localtime(time.time()))
|
||||||
|
return render_template('admin/monitor.html',
|
||||||
|
hostname=hostname,
|
||||||
|
system_version=system_version,
|
||||||
|
python_version=python_version,
|
||||||
|
cpus_percent=cpus_percent,
|
||||||
|
memory_usage=memory_usage,
|
||||||
|
cpu_count=cpu_count,
|
||||||
|
memory_used=memory_used,
|
||||||
|
memory_total=memory_total,
|
||||||
|
memory_free=memory_free,
|
||||||
|
boot_time=boot_time,
|
||||||
|
up_time_format=up_time_format,
|
||||||
|
disk_partitions_list=disk_partitions_list,
|
||||||
|
time_now=time_now
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# 图表 api
|
||||||
|
@admin_monitor_bp.get('/polling')
|
||||||
|
@authorize("admin:monitor:main")
|
||||||
|
def ajax_polling():
|
||||||
|
# 获取cup使用率
|
||||||
|
cpus_percent = psutil.cpu_percent(interval=0.1)
|
||||||
|
# 获取内存使用率
|
||||||
|
memory_information = psutil.virtual_memory()
|
||||||
|
memory_usage = memory_information.percent
|
||||||
|
time_now = time.strftime('%H:%M:%S ', time.localtime(time.time()))
|
||||||
|
return jsonify(cups_percent=cpus_percent, memory_used=memory_usage, time_now=time_now)
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
from flask import Blueprint, render_template, request, jsonify
|
||||||
|
|
||||||
|
from applications.common import curd
|
||||||
|
from applications.common.utils.http import success_api, fail_api
|
||||||
|
from applications.common.utils.rights import authorize
|
||||||
|
from applications.common.utils.validate import xss_escape
|
||||||
|
from applications.extensions import db
|
||||||
|
from applications.models import Power
|
||||||
|
from applications.schemas import PowerOutSchema2
|
||||||
|
|
||||||
|
admin_power = Blueprint('adminPower', __name__, url_prefix='/admin/power')
|
||||||
|
|
||||||
|
|
||||||
|
@admin_power.get('/')
|
||||||
|
@authorize("admin:power:main", log=True)
|
||||||
|
def index():
|
||||||
|
return render_template('admin/power/main.html')
|
||||||
|
|
||||||
|
|
||||||
|
@admin_power.post('/data')
|
||||||
|
@authorize("admin:power:main", log=True)
|
||||||
|
def data():
|
||||||
|
power = Power.query.all()
|
||||||
|
res = {
|
||||||
|
"data": curd.model_to_dicts(schema=PowerOutSchema2, data=power)
|
||||||
|
}
|
||||||
|
return jsonify(res)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_power.get('/add')
|
||||||
|
@authorize("admin:power:add", log=True)
|
||||||
|
def add():
|
||||||
|
return render_template('admin/power/add.html')
|
||||||
|
|
||||||
|
|
||||||
|
@admin_power.get('/selectParent')
|
||||||
|
@authorize("admin:power:main", log=True)
|
||||||
|
def select_parent():
|
||||||
|
power = Power.query.all()
|
||||||
|
res = curd.model_to_dicts(schema=PowerOutSchema2, data=power)
|
||||||
|
res.append({"powerId": 0, "powerName": "顶级权限", "parentId": -1})
|
||||||
|
res = {
|
||||||
|
"status": {"code": 200, "message": "默认"},
|
||||||
|
"data": res
|
||||||
|
|
||||||
|
}
|
||||||
|
return jsonify(res)
|
||||||
|
|
||||||
|
|
||||||
|
# 增加
|
||||||
|
@admin_power.post('/save')
|
||||||
|
@authorize("admin:power:add", log=True)
|
||||||
|
def save():
|
||||||
|
req = request.json
|
||||||
|
icon = xss_escape(req.get("icon"))
|
||||||
|
openType = xss_escape(req.get("openType"))
|
||||||
|
parentId = xss_escape(req.get("parentId"))
|
||||||
|
powerCode = xss_escape(req.get("powerCode"))
|
||||||
|
powerName = xss_escape(req.get("powerName"))
|
||||||
|
powerType = xss_escape(req.get("powerType"))
|
||||||
|
powerUrl = xss_escape(req.get("powerUrl"))
|
||||||
|
sort = xss_escape(req.get("sort"))
|
||||||
|
power = Power(
|
||||||
|
icon=icon,
|
||||||
|
open_type=openType,
|
||||||
|
parent_id=parentId,
|
||||||
|
code=powerCode,
|
||||||
|
name=powerName,
|
||||||
|
type=powerType,
|
||||||
|
url=powerUrl,
|
||||||
|
sort=sort,
|
||||||
|
enable=1
|
||||||
|
)
|
||||||
|
r = db.session.add(power)
|
||||||
|
db.session.commit()
|
||||||
|
return success_api(msg="成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 权限编辑
|
||||||
|
@admin_power.get('/edit/<int:_id>')
|
||||||
|
@authorize("admin:power:edit", log=True)
|
||||||
|
def edit(_id):
|
||||||
|
power = curd.get_one_by_id(Power, _id)
|
||||||
|
icon = str(power.icon).split()
|
||||||
|
if len(icon) == 2:
|
||||||
|
icon = icon[1]
|
||||||
|
else:
|
||||||
|
icon = None
|
||||||
|
return render_template('admin/power/edit.html', power=power, icon=icon)
|
||||||
|
|
||||||
|
|
||||||
|
# 权限更新
|
||||||
|
@admin_power.put('/update')
|
||||||
|
@authorize("admin:power:edit", log=True)
|
||||||
|
def update():
|
||||||
|
req_json = request.json
|
||||||
|
id = request.json.get("powerId")
|
||||||
|
data = {
|
||||||
|
"icon": xss_escape(req_json.get("icon")),
|
||||||
|
"open_type": xss_escape(req_json.get("openType")),
|
||||||
|
"parent_id": xss_escape(req_json.get("parentId")),
|
||||||
|
"code": xss_escape(req_json.get("powerCode")),
|
||||||
|
"name": xss_escape(req_json.get("powerName")),
|
||||||
|
"type": xss_escape(req_json.get("powerType")),
|
||||||
|
"url": xss_escape(req_json.get("powerUrl")),
|
||||||
|
"sort": xss_escape(req_json.get("sort"))
|
||||||
|
}
|
||||||
|
res = Power.query.filter_by(id=id).update(data)
|
||||||
|
db.session.commit()
|
||||||
|
if not res:
|
||||||
|
return fail_api(msg="更新权限失败")
|
||||||
|
return success_api(msg="更新权限成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 启用权限
|
||||||
|
@admin_power.put('/enable')
|
||||||
|
@authorize("admin:power:edit", log=True)
|
||||||
|
def enable():
|
||||||
|
_id = request.json.get('powerId')
|
||||||
|
if id:
|
||||||
|
res = curd.enable_status(Power, _id)
|
||||||
|
if not res:
|
||||||
|
return fail_api(msg="出错啦")
|
||||||
|
return success_api(msg="启用成功")
|
||||||
|
return fail_api(msg="数据错误")
|
||||||
|
|
||||||
|
|
||||||
|
# 禁用权限
|
||||||
|
@admin_power.put('/disable')
|
||||||
|
@authorize("admin:power:edit", log=True)
|
||||||
|
def dis_enable():
|
||||||
|
_id = request.json.get('powerId')
|
||||||
|
if id:
|
||||||
|
res = curd.disable_status(Power, _id)
|
||||||
|
if not res:
|
||||||
|
return fail_api(msg="出错啦")
|
||||||
|
return success_api(msg="禁用成功")
|
||||||
|
return fail_api(msg="数据错误")
|
||||||
|
|
||||||
|
|
||||||
|
# 权限删除
|
||||||
|
@admin_power.delete('/remove/<int:id>')
|
||||||
|
@authorize("admin:power:remove", log=True)
|
||||||
|
def remove(id):
|
||||||
|
power = Power.query.filter_by(id=id).first()
|
||||||
|
power.role = []
|
||||||
|
|
||||||
|
r = Power.query.filter_by(id=id).delete()
|
||||||
|
db.session.commit()
|
||||||
|
if r:
|
||||||
|
return success_api(msg="删除成功")
|
||||||
|
else:
|
||||||
|
return fail_api(msg="删除失败")
|
||||||
|
|
||||||
|
|
||||||
|
# 批量删除
|
||||||
|
@admin_power.delete('/batchRemove')
|
||||||
|
@authorize("admin:power:remove", log=True)
|
||||||
|
def batch_remove():
|
||||||
|
ids = request.form.getlist('ids[]')
|
||||||
|
for id in ids:
|
||||||
|
power = Power.query.filter_by(id=id).first()
|
||||||
|
power.role = []
|
||||||
|
|
||||||
|
r = Power.query.filter_by(id=id).delete()
|
||||||
|
db.session.commit()
|
||||||
|
return success_api(msg="批量删除成功")
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
from flask import Blueprint, render_template, request, jsonify
|
||||||
|
from flask_login import login_required
|
||||||
|
from applications.common.curd import model_to_dicts, enable_status, disable_status, get_one_by_id
|
||||||
|
from applications.common.helper import ModelFilter
|
||||||
|
from applications.common.utils.http import table_api, success_api, fail_api
|
||||||
|
from applications.common.utils.rights import authorize
|
||||||
|
from applications.common.utils.validate import xss_escape
|
||||||
|
from applications.extensions import db
|
||||||
|
from applications.models import Role, Power, User
|
||||||
|
from applications.schemas import RoleOutSchema, PowerOutSchema2
|
||||||
|
|
||||||
|
admin_role = Blueprint('adminRole', __name__, url_prefix='/admin/role')
|
||||||
|
|
||||||
|
|
||||||
|
# 用户管理
|
||||||
|
@admin_role.get('/')
|
||||||
|
@authorize("admin:role:main", log=True)
|
||||||
|
def main():
|
||||||
|
return render_template('admin/role/main.html')
|
||||||
|
|
||||||
|
|
||||||
|
# 表格数据
|
||||||
|
@admin_role.get('/data')
|
||||||
|
@authorize("admin:role:main", log=True)
|
||||||
|
def table():
|
||||||
|
# 获取请求参数
|
||||||
|
role_name = xss_escape(request.args.get('roleName', type=str))
|
||||||
|
role_code = xss_escape(request.args.get('roleCode', type=str))
|
||||||
|
# 查询参数构造
|
||||||
|
mf = ModelFilter()
|
||||||
|
if role_name:
|
||||||
|
mf.vague(field_name="name", value=role_name)
|
||||||
|
if role_code:
|
||||||
|
mf.vague(field_name="code", value=role_code)
|
||||||
|
# orm查询
|
||||||
|
# 使用分页获取data需要.items
|
||||||
|
role = Role.query.filter(mf.get_filter(Role)).layui_paginate()
|
||||||
|
count = role.total
|
||||||
|
# 返回api
|
||||||
|
return table_api(data=model_to_dicts(schema=RoleOutSchema, data=role.items), count=count)
|
||||||
|
|
||||||
|
|
||||||
|
# 角色增加
|
||||||
|
@admin_role.get('/add')
|
||||||
|
@authorize("admin:role:add", log=True)
|
||||||
|
def add():
|
||||||
|
return render_template('admin/role/add.html')
|
||||||
|
|
||||||
|
|
||||||
|
# 角色增加
|
||||||
|
@admin_role.post('/save')
|
||||||
|
@authorize("admin:role:add", log=True)
|
||||||
|
def save():
|
||||||
|
req = request.json
|
||||||
|
details = xss_escape(req.get("details"))
|
||||||
|
enable = xss_escape(req.get("enable"))
|
||||||
|
roleCode = xss_escape(req.get("roleCode"))
|
||||||
|
roleName = xss_escape(req.get("roleName"))
|
||||||
|
sort = xss_escape(req.get("sort"))
|
||||||
|
role = Role(
|
||||||
|
details=details,
|
||||||
|
enable=enable,
|
||||||
|
code=roleCode,
|
||||||
|
name=roleName,
|
||||||
|
sort=sort
|
||||||
|
)
|
||||||
|
db.session.add(role)
|
||||||
|
db.session.commit()
|
||||||
|
return success_api(msg="成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 角色授权
|
||||||
|
@admin_role.get('/power/<int:_id>')
|
||||||
|
@authorize("admin:role:power", log=True)
|
||||||
|
def power(_id):
|
||||||
|
return render_template('admin/role/power.html', id=_id)
|
||||||
|
|
||||||
|
|
||||||
|
# 获取角色权限
|
||||||
|
@admin_role.get('/getRolePower/<int:id>')
|
||||||
|
@authorize("admin:role:main", log=True)
|
||||||
|
def get_role_power(id):
|
||||||
|
role = Role.query.filter_by(id=id).first()
|
||||||
|
check_powers = role.power
|
||||||
|
check_powers_list = []
|
||||||
|
for cp in check_powers:
|
||||||
|
check_powers_list.append(cp.id)
|
||||||
|
powers = Power.query.all()
|
||||||
|
power_schema = PowerOutSchema2(many=True) # 用已继承ma.ModelSchema类的自定制类生成序列化类
|
||||||
|
output = power_schema.dump(powers) # 生成可序列化对象
|
||||||
|
for i in output:
|
||||||
|
if int(i.get("powerId")) in check_powers_list:
|
||||||
|
i["checkArr"] = "1"
|
||||||
|
else:
|
||||||
|
i["checkArr"] = "0"
|
||||||
|
res = {
|
||||||
|
"data": output,
|
||||||
|
"status": {"code": 200, "message": "默认"}
|
||||||
|
}
|
||||||
|
return jsonify(res)
|
||||||
|
|
||||||
|
|
||||||
|
# 保存角色权限
|
||||||
|
@admin_role.put('/saveRolePower')
|
||||||
|
@authorize("admin:role:edit", log=True)
|
||||||
|
def save_role_power():
|
||||||
|
req_form = request.form
|
||||||
|
power_ids = req_form.get("powerIds")
|
||||||
|
power_list = power_ids.split(',')
|
||||||
|
role_id = req_form.get("roleId")
|
||||||
|
role = Role.query.filter_by(id=role_id).first()
|
||||||
|
|
||||||
|
powers = Power.query.filter(Power.id.in_(power_list)).all()
|
||||||
|
role.power = powers
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
|
return success_api(msg="授权成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 角色编辑
|
||||||
|
@admin_role.get('/edit/<int:id>')
|
||||||
|
@authorize("admin:role:edit", log=True)
|
||||||
|
def edit(id):
|
||||||
|
r = get_one_by_id(model=Role, id=id)
|
||||||
|
return render_template('admin/role/edit.html', role=r)
|
||||||
|
|
||||||
|
|
||||||
|
# 更新角色
|
||||||
|
@admin_role.put('/update')
|
||||||
|
@authorize("admin:role:edit", log=True)
|
||||||
|
def update():
|
||||||
|
req_json = request.json
|
||||||
|
id = req_json.get("roleId")
|
||||||
|
data = {
|
||||||
|
"code": xss_escape(req_json.get("roleCode")),
|
||||||
|
"name": xss_escape(req_json.get("roleName")),
|
||||||
|
"sort": xss_escape(req_json.get("sort")),
|
||||||
|
"enable": xss_escape(req_json.get("enable")),
|
||||||
|
"details": xss_escape(req_json.get("details"))
|
||||||
|
}
|
||||||
|
role = Role.query.filter_by(id=id).update(data)
|
||||||
|
db.session.commit()
|
||||||
|
if not role:
|
||||||
|
return fail_api(msg="更新角色失败")
|
||||||
|
return success_api(msg="更新角色成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 启用用户
|
||||||
|
@admin_role.put('/enable')
|
||||||
|
@authorize("admin:role:edit", log=True)
|
||||||
|
def enable():
|
||||||
|
id = request.json.get('roleId')
|
||||||
|
if id:
|
||||||
|
res = enable_status(Role, id)
|
||||||
|
if not res:
|
||||||
|
return fail_api(msg="出错啦")
|
||||||
|
return success_api(msg="启动成功")
|
||||||
|
return fail_api(msg="数据错误")
|
||||||
|
|
||||||
|
|
||||||
|
# 禁用用户
|
||||||
|
@admin_role.put('/disable')
|
||||||
|
@authorize("admin:role:edit", log=True)
|
||||||
|
def dis_enable():
|
||||||
|
_id = request.json.get('roleId')
|
||||||
|
if _id:
|
||||||
|
res = disable_status(Role, _id)
|
||||||
|
if not res:
|
||||||
|
return fail_api(msg="出错啦")
|
||||||
|
return success_api(msg="禁用成功")
|
||||||
|
return fail_api(msg="数据错误")
|
||||||
|
|
||||||
|
|
||||||
|
# 角色删除
|
||||||
|
@admin_role.delete('/remove/<int:id>')
|
||||||
|
@authorize("admin:role:remove", log=True)
|
||||||
|
def remove(id):
|
||||||
|
role = Role.query.filter_by(id=id).first()
|
||||||
|
# 删除该角色的权限和用户
|
||||||
|
role.power = []
|
||||||
|
role.user = []
|
||||||
|
|
||||||
|
r = Role.query.filter_by(id=id).delete()
|
||||||
|
db.session.commit()
|
||||||
|
if not r:
|
||||||
|
return fail_api(msg="角色删除失败")
|
||||||
|
return success_api(msg="角色删除成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 批量删除
|
||||||
|
@admin_role.delete('/batchRemove')
|
||||||
|
@authorize("admin:role:remove", log=True)
|
||||||
|
@login_required
|
||||||
|
def batch_remove():
|
||||||
|
ids = request.form.getlist('ids[]')
|
||||||
|
for id in ids:
|
||||||
|
role = Role.query.filter_by(id=id).first()
|
||||||
|
# 删除该角色的权限和用户
|
||||||
|
role.power = []
|
||||||
|
role.user = []
|
||||||
|
|
||||||
|
r = Role.query.filter_by(id=id).delete()
|
||||||
|
db.session.commit()
|
||||||
|
return success_api(msg="批量删除成功")
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
from flask import Blueprint, request, render_template
|
||||||
|
from flask_apscheduler.utils import job_to_dict
|
||||||
|
|
||||||
|
from applications.common.tasks import tasks
|
||||||
|
from applications.common.tasks.tasks import task_list
|
||||||
|
from applications.common.utils.http import table_api, fail_api, success_api
|
||||||
|
from applications.extensions.init_apscheduler import scheduler
|
||||||
|
|
||||||
|
admin_task = Blueprint('adminTask', __name__, url_prefix='/admin/task')
|
||||||
|
|
||||||
|
|
||||||
|
@admin_task.route('/add_job', methods=['GET'])
|
||||||
|
def add_task():
|
||||||
|
scheduler.add_job(func=tasks.get(), id='4', args=(1, 1), trigger='interval', seconds=3,
|
||||||
|
replace_existing=True)
|
||||||
|
return '6'
|
||||||
|
|
||||||
|
|
||||||
|
@admin_task.get('/')
|
||||||
|
def main():
|
||||||
|
return render_template('admin/task/main.html')
|
||||||
|
|
||||||
|
|
||||||
|
@admin_task.route('/data', methods=['GET'])
|
||||||
|
def get_task(): # 获取
|
||||||
|
jobs = scheduler.get_jobs()
|
||||||
|
jobs_list = []
|
||||||
|
for job in jobs:
|
||||||
|
jobs_list.append(job_to_dict(job))
|
||||||
|
return table_api(data=jobs_list, count=len(jobs_list))
|
||||||
|
|
||||||
|
|
||||||
|
# 增加
|
||||||
|
@admin_task.get('/add')
|
||||||
|
def add():
|
||||||
|
return render_template('admin/task/add.html', task_list=task_list)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_task.post('/save')
|
||||||
|
def save():
|
||||||
|
_id = request.json.get("id")
|
||||||
|
name = request.json.get("id")
|
||||||
|
type = request.json.get("type")
|
||||||
|
functions = request.json.get("functions")
|
||||||
|
datetime = request.json.get("datetime")
|
||||||
|
time = request.json.get("time")
|
||||||
|
if not hasattr(tasks, functions):
|
||||||
|
return fail_api()
|
||||||
|
if type == 'date':
|
||||||
|
scheduler.add_job(
|
||||||
|
func=getattr(tasks, functions),
|
||||||
|
id=_id,
|
||||||
|
name=name,
|
||||||
|
args=(1, 1),
|
||||||
|
trigger=type,
|
||||||
|
run_date=datetime,
|
||||||
|
replace_existing=True)
|
||||||
|
elif type == 'interval':
|
||||||
|
scheduler.add_job(
|
||||||
|
func=getattr(tasks, functions),
|
||||||
|
id=_id,
|
||||||
|
name=name,
|
||||||
|
args=(1, 1),
|
||||||
|
trigger=type,
|
||||||
|
replace_existing=True)
|
||||||
|
elif type == 'cron':
|
||||||
|
scheduler.add_job(
|
||||||
|
func=getattr(tasks, functions),
|
||||||
|
id=_id,
|
||||||
|
name=name,
|
||||||
|
args=(1, 1),
|
||||||
|
trigger=type,
|
||||||
|
replace_existing=True)
|
||||||
|
|
||||||
|
return success_api()
|
||||||
|
|
||||||
|
|
||||||
|
# 恢复
|
||||||
|
@admin_task.put('/enable')
|
||||||
|
def enable():
|
||||||
|
_id = request.json.get('id')
|
||||||
|
# print(id)
|
||||||
|
if _id:
|
||||||
|
scheduler.resume_job(str(_id))
|
||||||
|
return success_api(msg="启动成功")
|
||||||
|
return fail_api(msg="数据错误")
|
||||||
|
|
||||||
|
|
||||||
|
# 暂停
|
||||||
|
@admin_task.put('/disable')
|
||||||
|
def dis_enable():
|
||||||
|
_id = request.json.get('id')
|
||||||
|
if _id:
|
||||||
|
scheduler.pause_job(str(_id))
|
||||||
|
return success_api(msg="暂停成功")
|
||||||
|
return fail_api(msg="数据错误")
|
||||||
|
|
||||||
|
|
||||||
|
@admin_task.delete('/remove/<int:_id>')
|
||||||
|
def remove_job(_id): # 移除
|
||||||
|
scheduler.remove_job(str(_id))
|
||||||
|
return success_api(msg="删除成功")
|
||||||
|
|
||||||
|
# scheduler.add_job(func=task1, id='2', args=(1, 1), trigger='cron', day_of_week='0-6', hour=18, minute=24,
|
||||||
|
# second=10, replace_existing=True)
|
||||||
|
|
||||||
|
# scheduler.add_job(func=task4, id='4', args=(2, 2), trigger='interval', seconds=3,
|
||||||
|
# replace_existing=True, misfire_grace_time=3)
|
||||||
|
|
||||||
|
# # trigger='interval' 表示是一个循环任务,每隔多久执行一次
|
||||||
|
# scheduler.add_job(func=task2, id='3', args=(2, 2), trigger='interval', seconds=3,
|
||||||
|
# replace_existing=True)
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
from flask import Blueprint, render_template, request
|
||||||
|
from flask_login import login_required, current_user
|
||||||
|
from sqlalchemy import desc
|
||||||
|
|
||||||
|
from applications.common import curd
|
||||||
|
from applications.common.curd import model_to_dicts, enable_status, disable_status
|
||||||
|
from applications.common.helper import ModelFilter
|
||||||
|
from applications.common.utils.http import table_api, fail_api, success_api
|
||||||
|
from applications.common.utils.rights import authorize
|
||||||
|
from applications.common.utils.validate import xss_escape
|
||||||
|
from applications.extensions import db
|
||||||
|
from applications.models import Role
|
||||||
|
from applications.models import User, AdminLog
|
||||||
|
from applications.schemas import UserOutSchema
|
||||||
|
|
||||||
|
admin_user = Blueprint('adminUser', __name__, url_prefix='/admin/user')
|
||||||
|
|
||||||
|
|
||||||
|
# 用户管理
|
||||||
|
@admin_user.get('/')
|
||||||
|
@authorize("admin:user:main", log=True)
|
||||||
|
def main():
|
||||||
|
return render_template('admin/user/main.html')
|
||||||
|
|
||||||
|
|
||||||
|
# 用户分页查询
|
||||||
|
@admin_user.get('/data')
|
||||||
|
@authorize("admin:user:main", log=True)
|
||||||
|
def data():
|
||||||
|
# 获取请求参数
|
||||||
|
real_name = xss_escape(request.args.get('realName', type=str))
|
||||||
|
username = xss_escape(request.args.get('username', type=str))
|
||||||
|
dept_id = request.args.get('deptId', type=int)
|
||||||
|
# 查询参数构造
|
||||||
|
mf = ModelFilter()
|
||||||
|
if real_name:
|
||||||
|
mf.contains(field_name="realname", value=real_name)
|
||||||
|
if username:
|
||||||
|
mf.contains(field_name="username", value=username)
|
||||||
|
if dept_id:
|
||||||
|
mf.exact(field_name="dept_id", value=dept_id)
|
||||||
|
# orm查询
|
||||||
|
# 使用分页获取data需要.items
|
||||||
|
user = User.query.filter(mf.get_filter(model=User)).layui_paginate()
|
||||||
|
count = user.total
|
||||||
|
# 返回api
|
||||||
|
return table_api(data=model_to_dicts(schema=UserOutSchema, data=user.items), count=count)
|
||||||
|
|
||||||
|
|
||||||
|
# 用户增加
|
||||||
|
@admin_user.get('/add')
|
||||||
|
@authorize("admin:user:add", log=True)
|
||||||
|
def add():
|
||||||
|
roles = Role.query.all()
|
||||||
|
return render_template('admin/user/add.html', roles=roles)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_user.post('/save')
|
||||||
|
@authorize("admin:user:add", log=True)
|
||||||
|
def save():
|
||||||
|
req_json = request.json
|
||||||
|
a = req_json.get("roleIds")
|
||||||
|
username = xss_escape(req_json.get('username'))
|
||||||
|
real_name = xss_escape(req_json.get('realName'))
|
||||||
|
password = xss_escape(req_json.get('password'))
|
||||||
|
role_ids = a.split(',')
|
||||||
|
|
||||||
|
if not username or not real_name or not password:
|
||||||
|
return fail_api(msg="账号姓名密码不得为空")
|
||||||
|
|
||||||
|
if bool(User.query.filter_by(username=username).count()):
|
||||||
|
return fail_api(msg="用户已经存在")
|
||||||
|
user = User(username=username, realname=real_name)
|
||||||
|
user.set_password(password)
|
||||||
|
db.session.add(user)
|
||||||
|
roles = Role.query.filter(Role.id.in_(role_ids)).all()
|
||||||
|
for r in roles:
|
||||||
|
user.role.append(r)
|
||||||
|
db.session.commit()
|
||||||
|
return success_api(msg="增加成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 删除用户
|
||||||
|
@admin_user.delete('/remove/<int:id>')
|
||||||
|
@authorize("admin:user:remove", log=True)
|
||||||
|
def delete(id):
|
||||||
|
user = User.query.filter_by(id=id).first()
|
||||||
|
user.role = []
|
||||||
|
|
||||||
|
res = User.query.filter_by(id=id).delete()
|
||||||
|
db.session.commit()
|
||||||
|
if not res:
|
||||||
|
return fail_api(msg="删除失败")
|
||||||
|
return success_api(msg="删除成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 编辑用户
|
||||||
|
@admin_user.get('/edit/<int:id>')
|
||||||
|
@authorize("admin:user:edit", log=True)
|
||||||
|
def edit(id):
|
||||||
|
user = curd.get_one_by_id(User,id)
|
||||||
|
roles = Role.query.all()
|
||||||
|
checked_roles = []
|
||||||
|
for r in user.role:
|
||||||
|
checked_roles.append(r.id)
|
||||||
|
return render_template('admin/user/edit.html', user=user, roles=roles, checked_roles=checked_roles)
|
||||||
|
|
||||||
|
|
||||||
|
# 编辑用户
|
||||||
|
@admin_user.put('/update')
|
||||||
|
@authorize("admin:user:edit", log=True)
|
||||||
|
def update():
|
||||||
|
req_json = request.json
|
||||||
|
a = xss_escape(req_json.get("roleIds"))
|
||||||
|
id = xss_escape(req_json.get("userId"))
|
||||||
|
username = xss_escape(req_json.get('username'))
|
||||||
|
real_name = xss_escape(req_json.get('realName'))
|
||||||
|
dept_id = xss_escape(req_json.get('deptId'))
|
||||||
|
role_ids = a.split(',')
|
||||||
|
User.query.filter_by(id=id).update({'username': username, 'realname': real_name, 'dept_id': dept_id})
|
||||||
|
u = User.query.filter_by(id=id).first()
|
||||||
|
|
||||||
|
roles = Role.query.filter(Role.id.in_(role_ids)).all()
|
||||||
|
u.role = roles
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
|
return success_api(msg="更新成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 个人中心
|
||||||
|
@admin_user.get('/center')
|
||||||
|
@login_required
|
||||||
|
def center():
|
||||||
|
user_info = current_user
|
||||||
|
user_logs = AdminLog.query.filter_by(url='/passport/login').filter_by(uid=current_user.id).order_by(
|
||||||
|
desc(AdminLog.create_time)).limit(10)
|
||||||
|
return render_template('admin/user/center.html', user_info=user_info, user_logs=user_logs)
|
||||||
|
|
||||||
|
|
||||||
|
# 修改头像
|
||||||
|
@admin_user.get('/profile')
|
||||||
|
@login_required
|
||||||
|
def profile():
|
||||||
|
return render_template('admin/user/profile.html')
|
||||||
|
|
||||||
|
|
||||||
|
# 修改头像
|
||||||
|
@admin_user.put('/updateAvatar')
|
||||||
|
@login_required
|
||||||
|
def update_avatar():
|
||||||
|
url = request.json.get("avatar").get("src")
|
||||||
|
r = User.query.filter_by(id=current_user.id).update({"avatar": url})
|
||||||
|
db.session.commit()
|
||||||
|
if not r:
|
||||||
|
return fail_api(msg="出错啦")
|
||||||
|
return success_api(msg="修改成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 修改当前用户信息
|
||||||
|
@admin_user.put('/updateInfo')
|
||||||
|
@login_required
|
||||||
|
def update_info():
|
||||||
|
req_json = request.json
|
||||||
|
r = User.query.filter_by(id=current_user.id).update(
|
||||||
|
{"realname": req_json.get("realName"), "remark": req_json.get("details")})
|
||||||
|
db.session.commit()
|
||||||
|
if not r:
|
||||||
|
return fail_api(msg="出错啦")
|
||||||
|
return success_api(msg="更新成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 修改当前用户密码
|
||||||
|
@admin_user.get('/editPassword')
|
||||||
|
@login_required
|
||||||
|
def edit_password():
|
||||||
|
return render_template('admin/user/edit_password.html')
|
||||||
|
|
||||||
|
|
||||||
|
# 修改当前用户密码
|
||||||
|
@admin_user.put('/editPassword')
|
||||||
|
@login_required
|
||||||
|
def edit_password_put():
|
||||||
|
res_json = request.json
|
||||||
|
if res_json.get("newPassword") == '':
|
||||||
|
return fail_api("新密码不得为空")
|
||||||
|
if res_json.get("newPassword") != res_json.get("confirmPassword"):
|
||||||
|
return fail_api("俩次密码不一样")
|
||||||
|
user = current_user
|
||||||
|
is_right = user.validate_password(res_json.get("oldPassword"))
|
||||||
|
if not is_right:
|
||||||
|
return fail_api("旧密码错误")
|
||||||
|
user.set_password(res_json.get("newPassword"))
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
return success_api("更改成功")
|
||||||
|
|
||||||
|
|
||||||
|
# 启用用户
|
||||||
|
@admin_user.put('/enable')
|
||||||
|
@authorize("admin:user:edit", log=True)
|
||||||
|
def enable():
|
||||||
|
_id = request.json.get('userId')
|
||||||
|
if _id:
|
||||||
|
res = enable_status(model=User, id=_id)
|
||||||
|
if not res:
|
||||||
|
return fail_api(msg="出错啦")
|
||||||
|
return success_api(msg="启动成功")
|
||||||
|
return fail_api(msg="数据错误")
|
||||||
|
|
||||||
|
|
||||||
|
# 禁用用户
|
||||||
|
@admin_user.put('/disable')
|
||||||
|
@authorize("admin:user:edit", log=True)
|
||||||
|
def dis_enable():
|
||||||
|
_id = request.json.get('userId')
|
||||||
|
if _id:
|
||||||
|
res = disable_status(model=User,id=_id)
|
||||||
|
if not res:
|
||||||
|
return fail_api(msg="出错啦")
|
||||||
|
return success_api(msg="禁用成功")
|
||||||
|
return fail_api(msg="数据错误")
|
||||||
|
|
||||||
|
|
||||||
|
# 批量删除
|
||||||
|
@admin_user.delete('/batchRemove')
|
||||||
|
@authorize("admin:user:remove", log=True)
|
||||||
|
def batch_remove():
|
||||||
|
ids = request.form.getlist('ids[]')
|
||||||
|
for id in ids:
|
||||||
|
user = User.query.filter_by(id=id).first()
|
||||||
|
user.role = []
|
||||||
|
|
||||||
|
res = User.query.filter_by(id=id).delete()
|
||||||
|
db.session.commit()
|
||||||
|
return success_api(msg="批量删除成功")
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
from flask import render_template, request
|
|
||||||
|
|
||||||
from models import DepartmentModel
|
|
||||||
from common.utils.rights import permission_required, view_logging_required
|
|
||||||
from applications.view import index_bp
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.get('/dept')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:dept:main")
|
|
||||||
def dept_index():
|
|
||||||
return render_template('admin/department/dept.html')
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.get('/dept/add')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:dept:add")
|
|
||||||
def add():
|
|
||||||
return render_template('admin/department/dept_add.html')
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.get('/dept/edit')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:dept:edit")
|
|
||||||
def edit():
|
|
||||||
dept_id = request.args.get("deptId", type=int)
|
|
||||||
dept = DepartmentModel.query.get(dept_id)
|
|
||||||
return render_template('admin/department/dept_edit.html', dept=dept)
|
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
from flask import Blueprint, render_template, request, jsonify
|
||||||
|
|
||||||
|
from applications.common import curd
|
||||||
|
from applications.common.utils import validate
|
||||||
|
from applications.common.utils.http import success_api, fail_api
|
||||||
|
from applications.common.utils.rights import authorize
|
||||||
|
from applications.common.utils.validate import xss_escape
|
||||||
|
from applications.extensions import db
|
||||||
|
from applications.models import Dept, User
|
||||||
|
from applications.schemas import DeptOutSchema
|
||||||
|
|
||||||
|
dept_bp = Blueprint('dept', __name__, url_prefix='/dept')
|
||||||
|
|
||||||
|
|
||||||
|
def register_dept_views(app):
|
||||||
|
app.register_blueprint(dept_bp)
|
||||||
|
|
||||||
|
|
||||||
|
@dept_bp.get('/')
|
||||||
|
@authorize("admin:dept:main", log=True)
|
||||||
|
def main():
|
||||||
|
return render_template('admin/dept/main.html')
|
||||||
|
|
||||||
|
|
||||||
|
@dept_bp.post('/data')
|
||||||
|
@authorize("admin:dept:main", log=True)
|
||||||
|
def data():
|
||||||
|
dept = Dept.query.order_by(Dept.sort).all()
|
||||||
|
power_data = curd.model_to_dicts(schema=DeptOutSchema, data=dept)
|
||||||
|
res = {
|
||||||
|
"data": power_data
|
||||||
|
}
|
||||||
|
return jsonify(res)
|
||||||
|
|
||||||
|
|
||||||
|
@dept_bp.get('/add')
|
||||||
|
@authorize("admin:dept:add", log=True)
|
||||||
|
def add():
|
||||||
|
return render_template('admin/dept/add.html')
|
||||||
|
|
||||||
|
|
||||||
|
@dept_bp.get('/tree')
|
||||||
|
@authorize("admin:dept:main", log=True)
|
||||||
|
def tree():
|
||||||
|
dept = Dept.query.order_by(Dept.sort).all()
|
||||||
|
power_data = curd.model_to_dicts(schema=DeptOutSchema, data=dept)
|
||||||
|
res = {
|
||||||
|
"status": {"code": 200, "message": "默认"},
|
||||||
|
"data": power_data
|
||||||
|
|
||||||
|
}
|
||||||
|
return jsonify(res)
|
||||||
|
|
||||||
|
|
||||||
|
@dept_bp.post('/save')
|
||||||
|
@authorize("admin:dept:add", log=True)
|
||||||
|
def save():
|
||||||
|
req_json = request.json
|
||||||
|
dept = Dept(
|
||||||
|
parent_id=req_json.get('parentId'),
|
||||||
|
dept_name=xss_escape(req_json.get('deptName')),
|
||||||
|
sort=xss_escape(req_json.get('sort')),
|
||||||
|
leader=xss_escape(req_json.get('leader')),
|
||||||
|
phone=xss_escape(req_json.get('phone')),
|
||||||
|
email=xss_escape(req_json.get('email')),
|
||||||
|
status=xss_escape(req_json.get('status')),
|
||||||
|
address=xss_escape(req_json.get('address'))
|
||||||
|
)
|
||||||
|
r = db.session.add(dept)
|
||||||
|
db.session.commit()
|
||||||
|
return success_api(msg="成功")
|
||||||
|
|
||||||
|
|
||||||
|
@dept_bp.get('/edit')
|
||||||
|
@authorize("admin:dept:edit", log=True)
|
||||||
|
def edit():
|
||||||
|
_id = request.args.get("deptId")
|
||||||
|
dept = curd.get_one_by_id(model=Dept, id=_id)
|
||||||
|
return render_template('admin/dept/edit.html', dept=dept)
|
||||||
|
|
||||||
|
|
||||||
|
# 启用
|
||||||
|
@dept_bp.put('/enable')
|
||||||
|
@authorize("admin:dept:edit", log=True)
|
||||||
|
def enable():
|
||||||
|
id = request.json.get('deptId')
|
||||||
|
if id:
|
||||||
|
enable = 1
|
||||||
|
d = Dept.query.filter_by(id=id).update({"status": enable})
|
||||||
|
if d:
|
||||||
|
db.session.commit()
|
||||||
|
return success_api(msg="启用成功")
|
||||||
|
return fail_api(msg="出错啦")
|
||||||
|
return fail_api(msg="数据错误")
|
||||||
|
|
||||||
|
|
||||||
|
# 禁用
|
||||||
|
@dept_bp.put('/disable')
|
||||||
|
@authorize("admin:dept:edit", log=True)
|
||||||
|
def dis_enable():
|
||||||
|
id = request.json.get('deptId')
|
||||||
|
if id:
|
||||||
|
enable = 0
|
||||||
|
d = Dept.query.filter_by(id=id).update({"status": enable})
|
||||||
|
if d:
|
||||||
|
db.session.commit()
|
||||||
|
return success_api(msg="禁用成功")
|
||||||
|
return fail_api(msg="出错啦")
|
||||||
|
return fail_api(msg="数据错误")
|
||||||
|
|
||||||
|
|
||||||
|
@dept_bp.put('/update')
|
||||||
|
@authorize("admin:dept:edit", log=True)
|
||||||
|
def update():
|
||||||
|
json = request.json
|
||||||
|
id = json.get("deptId"),
|
||||||
|
data = {
|
||||||
|
"dept_name": validate.xss_escape(json.get("deptName")),
|
||||||
|
"sort": validate.xss_escape(json.get("sort")),
|
||||||
|
"leader": validate.xss_escape(json.get("leader")),
|
||||||
|
"phone": validate.xss_escape(json.get("phone")),
|
||||||
|
"email": validate.xss_escape(json.get("email")),
|
||||||
|
"status": validate.xss_escape(json.get("status")),
|
||||||
|
"address": validate.xss_escape(json.get("address"))
|
||||||
|
}
|
||||||
|
d = Dept.query.filter_by(id=id).update(data)
|
||||||
|
if not d:
|
||||||
|
return fail_api(msg="更新失败")
|
||||||
|
db.session.commit()
|
||||||
|
return success_api(msg="更新成功")
|
||||||
|
|
||||||
|
|
||||||
|
@dept_bp.delete('/remove/<int:_id>')
|
||||||
|
@authorize("admin:dept:remove", log=True)
|
||||||
|
def remove(_id):
|
||||||
|
d = Dept.query.filter_by(id=_id).delete()
|
||||||
|
if not d:
|
||||||
|
return fail_api(msg="删除失败")
|
||||||
|
res = User.query.filter_by(dept_id=_id).update({"dept_id": None})
|
||||||
|
db.session.commit()
|
||||||
|
if res:
|
||||||
|
return success_api(msg="删除成功")
|
||||||
|
else:
|
||||||
|
return fail_api(msg="删除失败")
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
from flask import render_template
|
|
||||||
|
|
||||||
from applications.view import index_bp
|
|
||||||
from common.utils.rights import view_logging_required, permission_required
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.get('/file')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:file:main")
|
|
||||||
def file_index():
|
|
||||||
return render_template('admin/file/photo.html')
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.get('/file/photo/add')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:file:main")
|
|
||||||
def file_photo_add():
|
|
||||||
return render_template('admin/file/photo_add.html')
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
from flask import Blueprint
|
|
||||||
from flask import render_template
|
|
||||||
from flask_login import login_required, current_user
|
|
||||||
|
|
||||||
index_bp = Blueprint('index', __name__)
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.route('/')
|
|
||||||
def index():
|
|
||||||
return render_template('index/index.html')
|
|
||||||
|
|
||||||
|
|
||||||
# 首页
|
|
||||||
@index_bp.get('/admin/')
|
|
||||||
@login_required
|
|
||||||
def admin_index():
|
|
||||||
return render_template('index/admin_index.html', user=current_user)
|
|
||||||
|
|
||||||
|
|
||||||
# 控制台页面
|
|
||||||
@index_bp.get('/admin/welcome')
|
|
||||||
@login_required
|
|
||||||
def welcome():
|
|
||||||
return render_template('index/welcome.html')
|
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
from applications.view.index.index import index_bp
|
||||||
|
|
||||||
|
from . import index
|
||||||
|
|
||||||
|
|
||||||
|
def register_index_views(app):
|
||||||
|
"""
|
||||||
|
初始化蓝图
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
app.register_blueprint(index_bp)
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
from flask import render_template, Blueprint
|
||||||
|
|
||||||
|
index_bp = Blueprint('Index', __name__, url_prefix='/')
|
||||||
|
|
||||||
|
|
||||||
|
@index_bp.route('/')
|
||||||
|
def index():
|
||||||
|
return render_template('index/index.html')
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
from flask import Blueprint, request, render_template
|
|
||||||
from sqlalchemy import desc
|
|
||||||
|
|
||||||
from common.utils.http import table_api
|
|
||||||
from common.utils.rights import permission_required
|
|
||||||
from models import LogModel
|
|
||||||
|
|
||||||
logs_bp = Blueprint('logs', __name__, url_prefix='/logs')
|
|
||||||
|
|
||||||
|
|
||||||
@logs_bp.get('/')
|
|
||||||
@permission_required("admin:log:main")
|
|
||||||
def index():
|
|
||||||
return render_template('admin/logs_temp/main.html')
|
|
||||||
|
|
||||||
|
|
||||||
@logs_bp.get('/login_log')
|
|
||||||
@permission_required("admin:log:main")
|
|
||||||
def login_log():
|
|
||||||
page = request.args.get('page', type=int)
|
|
||||||
limit = request.args.get('limit', type=int)
|
|
||||||
log_paginate = LogModel.query.filter_by(
|
|
||||||
url='/api/v1/passport/login').order_by(
|
|
||||||
desc(LogModel.create_at)).paginate(
|
|
||||||
page=page, per_page=limit, error_out=False)
|
|
||||||
data = [
|
|
||||||
{
|
|
||||||
'id': item.id,
|
|
||||||
'method': item.method,
|
|
||||||
'uid': item.uid,
|
|
||||||
'url': item.url,
|
|
||||||
'desc': item.desc,
|
|
||||||
'ip': item.ip,
|
|
||||||
'success': item.success,
|
|
||||||
'user_agent': item.user_agent,
|
|
||||||
'create_at': item.create_at.strftime('%Y-%m-%d %H:%M:%S'),
|
|
||||||
} for item in log_paginate.items
|
|
||||||
]
|
|
||||||
|
|
||||||
return table_api(result={'items': data,
|
|
||||||
'total': log_paginate.total, },
|
|
||||||
code=0)
|
|
||||||
|
|
||||||
|
|
||||||
@logs_bp.get('/access_log')
|
|
||||||
@permission_required("admin:log:main")
|
|
||||||
def operate_log():
|
|
||||||
page = request.args.get('page', type=int)
|
|
||||||
limit = request.args.get('limit', type=int)
|
|
||||||
log_paginate = LogModel.query.filter(
|
|
||||||
LogModel.url != '/api/v1/passport/login').order_by(
|
|
||||||
desc(LogModel.create_at)).paginate(
|
|
||||||
page=page, per_page=limit, error_out=False)
|
|
||||||
data = [
|
|
||||||
{
|
|
||||||
'id': item.id,
|
|
||||||
'method': item.method,
|
|
||||||
'uid': item.uid,
|
|
||||||
'url': item.url,
|
|
||||||
'desc': item.desc,
|
|
||||||
'ip': item.ip,
|
|
||||||
'success': item.success,
|
|
||||||
'user_agent': item.user_agent,
|
|
||||||
'create_at': item.create_at.strftime('%Y-%m-%d %H:%M:%S'),
|
|
||||||
} for item in log_paginate.items
|
|
||||||
]
|
|
||||||
return table_api(result={'items': data,
|
|
||||||
'total': log_paginate.total, },
|
|
||||||
code=0)
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
from flask import session, redirect, render_template, url_for
|
|
||||||
from flask_login import login_required, logout_user, current_user
|
|
||||||
|
|
||||||
from common.gen_captcha import get_captcha_image
|
|
||||||
from common.utils.http import success_api
|
|
||||||
|
|
||||||
# 获取验证码
|
|
||||||
from applications.view import index_bp
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.get('/passport/getCaptcha')
|
|
||||||
def get_captcha():
|
|
||||||
resp, code = get_captcha_image()
|
|
||||||
session["code"] = code
|
|
||||||
return resp
|
|
||||||
|
|
||||||
|
|
||||||
# 退出登录
|
|
||||||
@index_bp.post('/passport/logout')
|
|
||||||
@login_required
|
|
||||||
def logout():
|
|
||||||
logout_user()
|
|
||||||
session.pop('permissions')
|
|
||||||
return success_api(message="注销成功")
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.get('/passport/login')
|
|
||||||
def login():
|
|
||||||
if current_user.is_authenticated:
|
|
||||||
return redirect(url_for('admin.index'))
|
|
||||||
# TODO 分离视图操作 最终实现接口登录与视图登录两套逻辑
|
|
||||||
return render_template('index/login.html')
|
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
from flask import Blueprint, session, redirect, url_for, render_template, request
|
||||||
|
from flask_login import current_user, login_user, login_required, logout_user
|
||||||
|
|
||||||
|
from applications.common import admin as index_curd
|
||||||
|
from applications.common.admin_log import login_log
|
||||||
|
from applications.common.utils.http import fail_api, success_api
|
||||||
|
from applications.models import User
|
||||||
|
|
||||||
|
passport_bp = Blueprint('passport', __name__, url_prefix='/passport')
|
||||||
|
|
||||||
|
|
||||||
|
def register_passport_views(app):
|
||||||
|
app.register_blueprint(passport_bp)
|
||||||
|
|
||||||
|
|
||||||
|
# 获取验证码
|
||||||
|
@passport_bp.get('/getCaptcha')
|
||||||
|
def get_captcha():
|
||||||
|
resp, code = index_curd.get_captcha()
|
||||||
|
session["code"] = code
|
||||||
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
# 登录
|
||||||
|
@passport_bp.get('/login')
|
||||||
|
def login():
|
||||||
|
if current_user.is_authenticated:
|
||||||
|
return redirect(url_for('admin.index'))
|
||||||
|
return render_template('admin/login.html')
|
||||||
|
|
||||||
|
|
||||||
|
# 登录
|
||||||
|
@passport_bp.post('/login')
|
||||||
|
def login_post():
|
||||||
|
req = request.form
|
||||||
|
username = req.get('username')
|
||||||
|
password = req.get('password')
|
||||||
|
code = req.get('captcha').__str__().lower()
|
||||||
|
|
||||||
|
if not username or not password or not code:
|
||||||
|
return fail_api(msg="用户名或密码没有输入")
|
||||||
|
s_code = session.get("code", None)
|
||||||
|
session["code"] = None
|
||||||
|
|
||||||
|
if not all([code, s_code]):
|
||||||
|
return fail_api(msg="参数错误")
|
||||||
|
|
||||||
|
if code != s_code:
|
||||||
|
return fail_api(msg="验证码错误")
|
||||||
|
user = User.query.filter_by(username=username).first()
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
return fail_api(msg="不存在的用户")
|
||||||
|
|
||||||
|
if user.enable == 0:
|
||||||
|
return fail_api(msg="用户被暂停使用")
|
||||||
|
|
||||||
|
if username == user.username and user.validate_password(password):
|
||||||
|
# 登录
|
||||||
|
login_user(user)
|
||||||
|
# 记录登录日志
|
||||||
|
login_log(request, uid=user.id, is_access=True)
|
||||||
|
# 存入权限
|
||||||
|
index_curd.add_auth_session()
|
||||||
|
return success_api(msg="登录成功")
|
||||||
|
login_log(request, uid=user.id, is_access=False)
|
||||||
|
return fail_api(msg="用户名或密码错误")
|
||||||
|
|
||||||
|
|
||||||
|
# 退出登录
|
||||||
|
@passport_bp.post('/logout')
|
||||||
|
@login_required
|
||||||
|
def logout():
|
||||||
|
logout_user()
|
||||||
|
session.pop('permissions')
|
||||||
|
return success_api(msg="注销成功")
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
from flask import render_template
|
|
||||||
|
|
||||||
from common.utils.rights import permission_required, view_logging_required
|
|
||||||
from models import RightModel
|
|
||||||
from applications.view import index_bp
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.get('/rights/')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:power:main")
|
|
||||||
def rights_index():
|
|
||||||
return render_template('admin/rights/rights.html')
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.get('/rights/power/<int:power_id>')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:power:edit")
|
|
||||||
def rights_edit(power_id):
|
|
||||||
power = RightModel.query.filter_by(id=power_id).first()
|
|
||||||
icon = str(power.icon).split()
|
|
||||||
if len(icon) == 2:
|
|
||||||
icon = icon[1]
|
|
||||||
else:
|
|
||||||
icon = None
|
|
||||||
return render_template('admin/rights/rights_edit.html', power=power, icon=icon)
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.get('/rights/add')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:power:main")
|
|
||||||
def rights_add():
|
|
||||||
return render_template('admin/rights/rights_add.html')
|
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
from flask import Blueprint, Flask
|
||||||
|
|
||||||
|
rights_bp = Blueprint('rights', __name__, url_prefix='/rights')
|
||||||
|
|
||||||
|
from . import routes
|
||||||
|
|
||||||
|
|
||||||
|
def register_rights_view(app: Flask):
|
||||||
|
app.register_blueprint(rights_bp)
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# 渲染配置
|
||||||
|
from flask import jsonify
|
||||||
|
from flask_login import login_required
|
||||||
|
|
||||||
|
from . import rights_bp
|
||||||
|
from ...common import admin
|
||||||
|
|
||||||
|
|
||||||
|
@rights_bp.get('/configs')
|
||||||
|
@login_required
|
||||||
|
def configs():
|
||||||
|
return admin.get_render_config()
|
||||||
|
|
||||||
|
|
||||||
|
# 菜单
|
||||||
|
@rights_bp.get('/menu')
|
||||||
|
@login_required
|
||||||
|
def menu():
|
||||||
|
menu_tree = admin.make_menu_tree()
|
||||||
|
return jsonify(menu_tree)
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
from flask import Blueprint, render_template
|
|
||||||
|
|
||||||
from common.utils.rights import permission_required, view_logging_required
|
|
||||||
|
|
||||||
from models import RoleModel
|
|
||||||
|
|
||||||
role_bp = Blueprint('role', __name__, url_prefix='/admin/role')
|
|
||||||
|
|
||||||
|
|
||||||
# 角色而管理
|
|
||||||
@role_bp.get('/')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:role:main")
|
|
||||||
def main():
|
|
||||||
return render_template('admin/roles/roles.html')
|
|
||||||
|
|
||||||
|
|
||||||
# 角色授权操作
|
|
||||||
@role_bp.get('/power/<int:role_id>')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:role:power")
|
|
||||||
def power(role_id):
|
|
||||||
return render_template('admin/roles/roles_power.html', role_id=role_id)
|
|
||||||
|
|
||||||
|
|
||||||
# 角色编辑
|
|
||||||
@role_bp.get('/edit/<int:role_id>')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:role:edit")
|
|
||||||
def role_editor(role_id):
|
|
||||||
role = RoleModel.query.filter_by(id=role_id).first()
|
|
||||||
return render_template('admin/roles/roles_edit.html', role=role)
|
|
||||||
|
|
||||||
|
|
||||||
@role_bp.get('/add')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:role:edit")
|
|
||||||
def role_add():
|
|
||||||
return render_template('admin/roles/roles_add.html')
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
from flask import render_template
|
|
||||||
from flask_login import login_required, current_user
|
|
||||||
from sqlalchemy import desc
|
|
||||||
|
|
||||||
from common.utils.rights import permission_required, view_logging_required
|
|
||||||
from models import LogModel, RoleModel, UserModel
|
|
||||||
from . import index_bp
|
|
||||||
|
|
||||||
|
|
||||||
# 用户增加
|
|
||||||
@index_bp.get('/users/')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:user:main")
|
|
||||||
def users_main():
|
|
||||||
return render_template('admin/users/users.html')
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.get('/users/add')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:user:add")
|
|
||||||
def users_add_view():
|
|
||||||
roles = RoleModel.query.all()
|
|
||||||
return render_template('admin/users/users_add.html', roles=roles)
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.get('/users/<user_id>')
|
|
||||||
@view_logging_required
|
|
||||||
@permission_required("admin:user:edit")
|
|
||||||
def users_user_id_view(user_id):
|
|
||||||
# 获取编辑用户信息
|
|
||||||
user = UserModel.query.filter_by(id=user_id).first()
|
|
||||||
roles = RoleModel.query.all()
|
|
||||||
checked_roles = []
|
|
||||||
for r in user.role:
|
|
||||||
checked_roles.append(r.id)
|
|
||||||
return render_template('admin/users/users_edit.html', user=user, roles=roles, checked_roles=checked_roles)
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.get('/users/center')
|
|
||||||
@login_required
|
|
||||||
def users_center():
|
|
||||||
user_logs = LogModel.query.filter_by(url='/passport/login').filter_by(uid=current_user.id).order_by(
|
|
||||||
desc(LogModel.create_at)).limit(10)
|
|
||||||
return render_template('admin/users/profile.html', user_info=current_user, user_logs=user_logs)
|
|
||||||
|
|
||||||
|
|
||||||
@index_bp.get('/users/avatar')
|
|
||||||
def users_avatar_view():
|
|
||||||
return render_template('admin/users/profile_avatar.html')
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
def register_api(view, endpoint, url, pk='id', pk_type='int', app=None):
|
|
||||||
view_func = view.as_view(endpoint)
|
|
||||||
app.add_url_rule(url, defaults={pk: None}, view_func=view_func, methods=['GET', ])
|
|
||||||
app.add_url_rule(url, view_func=view_func, methods=['POST', ])
|
|
||||||
app.add_url_rule(f'{url}<{pk_type}:{pk}>', view_func=view_func, methods=['GET', 'PUT', 'DELETE'])
|
|
||||||
@@ -1,504 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
为了解决 flask_uploads 与 Werkzeug 2.0.1 冲突而直接复制源码进行适配
|
|
||||||
原始地址: https://github.com/maxcountryman/flask-uploads/blob/master/flask_uploads.py
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sys
|
|
||||||
|
|
||||||
PY3 = sys.version_info[0] == 3
|
|
||||||
|
|
||||||
if PY3:
|
|
||||||
string_types = str,
|
|
||||||
else:
|
|
||||||
string_types = basestring,
|
|
||||||
|
|
||||||
import os.path
|
|
||||||
import posixpath
|
|
||||||
|
|
||||||
from flask import current_app, send_from_directory, abort, url_for
|
|
||||||
from itertools import chain
|
|
||||||
from werkzeug.datastructures import FileStorage
|
|
||||||
from werkzeug.utils import secure_filename
|
|
||||||
|
|
||||||
from flask import Blueprint
|
|
||||||
|
|
||||||
# Extension presets
|
|
||||||
|
|
||||||
#: This just contains plain text files (.txt).
|
|
||||||
TEXT = ('txt',)
|
|
||||||
|
|
||||||
#: This contains various office document formats (.rtf, .odf, .ods, .gnumeric,
|
|
||||||
#: .abw, .doc, .docx, .xls, and .xlsx). Note that the macro-enabled versions
|
|
||||||
#: of Microsoft Office 2007 files are not included.
|
|
||||||
DOCUMENTS = tuple('rtf odf ods gnumeric abw doc docx xls xlsx'.split())
|
|
||||||
|
|
||||||
#: This contains basic image types that are viewable from most browsers (.jpg,
|
|
||||||
#: .jpe, .jpeg, .png, .gif, .svg, and .bmp).
|
|
||||||
IMAGES = tuple('jpg jpe jpeg png gif svg bmp'.split())
|
|
||||||
|
|
||||||
#: This contains audio file types (.wav, .mp3, .aac, .ogg, .oga, and .flac).
|
|
||||||
AUDIO = tuple('wav mp3 aac ogg oga flac'.split())
|
|
||||||
|
|
||||||
#: This is for structured data files (.csv, .ini, .json, .plist, .xml, .yaml,
|
|
||||||
#: and .yml).
|
|
||||||
DATA = tuple('csv ini json plist xml yaml yml'.split())
|
|
||||||
|
|
||||||
#: This contains various types of scripts (.js, .php, .pl, .py .rb, and .sh).
|
|
||||||
#: If your Web server has PHP installed and set to auto-run, you might want to
|
|
||||||
#: add ``php`` to the DENY setting.
|
|
||||||
SCRIPTS = tuple('js php pl py rb sh'.split())
|
|
||||||
|
|
||||||
#: This contains archive and compression formats (.gz, .bz2, .zip, .tar,
|
|
||||||
#: .tgz, .txz, and .7z).
|
|
||||||
ARCHIVES = tuple('gz bz2 zip tar tgz txz 7z'.split())
|
|
||||||
|
|
||||||
#: This contains shared libraries and executable files (.so, .exe and .dll).
|
|
||||||
#: Most of the time, you will not want to allow this - it's better suited for
|
|
||||||
#: use with `AllExcept`.
|
|
||||||
EXECUTABLES = tuple('so exe dll'.split())
|
|
||||||
|
|
||||||
#: The default allowed extensions - `TEXT`, `DOCUMENTS`, `DATA`, and `IMAGES`.
|
|
||||||
DEFAULTS = TEXT + DOCUMENTS + IMAGES + DATA
|
|
||||||
|
|
||||||
|
|
||||||
class UploadNotAllowed(Exception):
|
|
||||||
"""
|
|
||||||
This exception is raised if the upload was not allowed. You should catch
|
|
||||||
it in your view code and display an appropriate message to the user.
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
def tuple_from(*iters):
|
|
||||||
return tuple(itertools.chain(*iters))
|
|
||||||
|
|
||||||
|
|
||||||
def extension(filename):
|
|
||||||
ext = os.path.splitext(filename)[1]
|
|
||||||
if ext.startswith('.'):
|
|
||||||
# os.path.splitext retains . separator
|
|
||||||
ext = ext[1:]
|
|
||||||
return ext
|
|
||||||
|
|
||||||
|
|
||||||
def lowercase_ext(filename):
|
|
||||||
"""
|
|
||||||
This is a helper used by UploadSet.save to provide lowercase extensions for
|
|
||||||
all processed files, to compare with configured extensions in the same
|
|
||||||
case.
|
|
||||||
|
|
||||||
.. versionchanged:: 0.1.4
|
|
||||||
Filenames without extensions are no longer lowercased, only the
|
|
||||||
extension is returned in lowercase, if an extension exists.
|
|
||||||
|
|
||||||
:param filename: The filename to ensure has a lowercase extension.
|
|
||||||
"""
|
|
||||||
if '.' in filename:
|
|
||||||
main, ext = os.path.splitext(filename)
|
|
||||||
return main + ext.lower()
|
|
||||||
# For consistency with os.path.splitext,
|
|
||||||
# do not treat a filename without an extension as an extension.
|
|
||||||
# That is, do not return filename.lower().
|
|
||||||
return filename
|
|
||||||
|
|
||||||
|
|
||||||
def addslash(url):
|
|
||||||
if url.endswith('/'):
|
|
||||||
return url
|
|
||||||
return url + '/'
|
|
||||||
|
|
||||||
|
|
||||||
def patch_request_class(app, size=64 * 1024 * 1024):
|
|
||||||
"""
|
|
||||||
By default, Flask will accept uploads to an arbitrary size. While Werkzeug
|
|
||||||
switches uploads from memory to a temporary file when they hit 500 KiB,
|
|
||||||
it's still possible for someone to overload your disk space with a
|
|
||||||
gigantic file.
|
|
||||||
|
|
||||||
This patches the app's request class's
|
|
||||||
`~werkzeug.BaseRequest.max_content_length` attribute so that any upload
|
|
||||||
larger than the given size is rejected with an HTTP error.
|
|
||||||
|
|
||||||
.. note::
|
|
||||||
|
|
||||||
In Flask 0.6, you can do this by setting the `MAX_CONTENT_LENGTH`
|
|
||||||
setting, without patching the request class. To emulate this behavior,
|
|
||||||
you can pass `None` as the size (you must pass it explicitly). That is
|
|
||||||
the best way to call this function, as it won't break the Flask 0.6
|
|
||||||
functionality if it exists.
|
|
||||||
|
|
||||||
.. versionchanged:: 0.1.1
|
|
||||||
|
|
||||||
:param app: The app to patch the request class of.
|
|
||||||
:param size: The maximum size to accept, in bytes. The default is 64 MiB.
|
|
||||||
If it is `None`, the app's `MAX_CONTENT_LENGTH` configuration
|
|
||||||
setting will be used to patch.
|
|
||||||
"""
|
|
||||||
if size is None:
|
|
||||||
if isinstance(app.request_class.__dict__['max_content_length'],
|
|
||||||
property):
|
|
||||||
return
|
|
||||||
size = app.config.get('MAX_CONTENT_LENGTH')
|
|
||||||
reqclass = app.request_class
|
|
||||||
patched = type(reqclass.__name__, (reqclass,),
|
|
||||||
{'max_content_length': size})
|
|
||||||
app.request_class = patched
|
|
||||||
|
|
||||||
|
|
||||||
def config_for_set(uset, app, defaults=None):
|
|
||||||
"""
|
|
||||||
This is a helper function for `configure_uploads` that extracts the
|
|
||||||
configuration for a single set.
|
|
||||||
|
|
||||||
:param uset: The upload set.
|
|
||||||
:param app: The app to load the configuration from.
|
|
||||||
:param defaults: A dict with keys `url` and `dest` from the
|
|
||||||
`UPLOADS_DEFAULT_DEST` and `DEFAULT_UPLOADS_URL`
|
|
||||||
settings.
|
|
||||||
"""
|
|
||||||
config = app.config
|
|
||||||
prefix = 'UPLOADED_%s_' % uset.name.upper()
|
|
||||||
using_defaults = False
|
|
||||||
if defaults is None:
|
|
||||||
defaults = dict(dest=None, url=None)
|
|
||||||
|
|
||||||
allow_extns = tuple(config.get(prefix + 'ALLOW', ()))
|
|
||||||
deny_extns = tuple(config.get(prefix + 'DENY', ()))
|
|
||||||
destination = config.get(prefix + 'DEST')
|
|
||||||
base_url = config.get(prefix + 'URL')
|
|
||||||
|
|
||||||
if destination is None:
|
|
||||||
# the upload set's destination wasn't given
|
|
||||||
if uset.default_dest:
|
|
||||||
# use the "default_dest" callable
|
|
||||||
destination = uset.default_dest(app)
|
|
||||||
if destination is None: # still
|
|
||||||
# use the default dest from the config
|
|
||||||
if defaults['dest'] is not None:
|
|
||||||
using_defaults = True
|
|
||||||
destination = os.path.join(defaults['dest'], uset.name)
|
|
||||||
else:
|
|
||||||
raise RuntimeError("no destination for set %s" % uset.name)
|
|
||||||
|
|
||||||
if base_url is None and using_defaults and defaults['url']:
|
|
||||||
base_url = addslash(defaults['url']) + uset.name + '/'
|
|
||||||
|
|
||||||
return UploadConfiguration(destination, base_url, allow_extns, deny_extns)
|
|
||||||
|
|
||||||
|
|
||||||
def configure_uploads(app, upload_sets):
|
|
||||||
"""
|
|
||||||
Call this after the app has been configured. It will go through all the
|
|
||||||
upload sets, get their configuration, and store the configuration on the
|
|
||||||
app. It will also register the uploads module if it hasn't been set. This
|
|
||||||
can be called multiple times with different upload sets.
|
|
||||||
|
|
||||||
.. versionchanged:: 0.1.3
|
|
||||||
The uploads module/blueprint will only be registered if it is needed
|
|
||||||
to serve the upload sets.
|
|
||||||
|
|
||||||
:param app: The `~flask.Flask` instance to get the configuration from.
|
|
||||||
:param upload_sets: The `UploadSet` instances to configure.
|
|
||||||
"""
|
|
||||||
if isinstance(upload_sets, UploadSet):
|
|
||||||
upload_sets = (upload_sets,)
|
|
||||||
|
|
||||||
if not hasattr(app, 'upload_set_config'):
|
|
||||||
app.upload_set_config = {}
|
|
||||||
set_config = app.upload_set_config
|
|
||||||
defaults = dict(dest=app.config.get('UPLOADS_DEFAULT_DEST'),
|
|
||||||
url=app.config.get('UPLOADS_DEFAULT_URL'))
|
|
||||||
|
|
||||||
for uset in upload_sets:
|
|
||||||
config = config_for_set(uset, app, defaults)
|
|
||||||
set_config[uset.name] = config
|
|
||||||
|
|
||||||
should_serve = any(s.base_url is None for s in set_config.values())
|
|
||||||
if '_uploads' not in app.blueprints and should_serve:
|
|
||||||
app.register_blueprint(uploads_mod)
|
|
||||||
|
|
||||||
|
|
||||||
class All(object):
|
|
||||||
"""
|
|
||||||
This type can be used to allow all extensions. There is a predefined
|
|
||||||
instance named `ALL`.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __contains__(self, item):
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
#: This "contains" all items. You can use it to allow all extensions to be
|
|
||||||
#: uploaded.
|
|
||||||
ALL = All()
|
|
||||||
|
|
||||||
|
|
||||||
class AllExcept(object):
|
|
||||||
"""
|
|
||||||
This can be used to allow all file types except certain ones. For example,
|
|
||||||
to ban .exe and .iso files, pass::
|
|
||||||
|
|
||||||
AllExcept(('exe', 'iso'))
|
|
||||||
|
|
||||||
to the `UploadSet` constructor as `extensions`. You can use any container,
|
|
||||||
for example::
|
|
||||||
|
|
||||||
AllExcept(SCRIPTS + EXECUTABLES)
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, items):
|
|
||||||
self.items = items
|
|
||||||
|
|
||||||
def __contains__(self, item):
|
|
||||||
return item not in self.items
|
|
||||||
|
|
||||||
|
|
||||||
class UploadConfiguration(object):
|
|
||||||
"""
|
|
||||||
This holds the configuration for a single `UploadSet`. The constructor's
|
|
||||||
arguments are also the attributes.
|
|
||||||
|
|
||||||
:param destination: The directory to save files to.
|
|
||||||
:param base_url: The URL (ending with a /) that files can be downloaded
|
|
||||||
from. If this is `None`, Flask-Uploads will serve the
|
|
||||||
files itself.
|
|
||||||
:param allow: A list of extensions to allow, even if they're not in the
|
|
||||||
`UploadSet` extensions list.
|
|
||||||
:param deny: A list of extensions to deny, even if they are in the
|
|
||||||
`UploadSet` extensions list.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, destination, base_url=None, allow=(), deny=()):
|
|
||||||
self.destination = destination
|
|
||||||
self.base_url = base_url
|
|
||||||
self.allow = allow
|
|
||||||
self.deny = deny
|
|
||||||
|
|
||||||
@property
|
|
||||||
def tuple(self):
|
|
||||||
return (self.destination, self.base_url, self.allow, self.deny)
|
|
||||||
|
|
||||||
def __eq__(self, other):
|
|
||||||
return self.tuple == other.tuple
|
|
||||||
|
|
||||||
|
|
||||||
class UploadSet(object):
|
|
||||||
"""
|
|
||||||
This represents a single set of uploaded files. Each upload set is
|
|
||||||
independent of the others. This can be reused across multiple application
|
|
||||||
instances, as all configuration is stored on the application object itself
|
|
||||||
and found with `flask.current_app`.
|
|
||||||
|
|
||||||
:param name: The name of this upload set. It defaults to ``files``, but
|
|
||||||
you can pick any alphanumeric name you want. (For simplicity,
|
|
||||||
it's best to use a plural noun.)
|
|
||||||
:param extensions: The extensions to allow uploading in this set. The
|
|
||||||
easiest way to do this is to add together the extension
|
|
||||||
presets (for example, ``TEXT + DOCUMENTS + IMAGES``).
|
|
||||||
It can be overridden by the configuration with the
|
|
||||||
`UPLOADED_X_ALLOW` and `UPLOADED_X_DENY` configuration
|
|
||||||
parameters. The default is `DEFAULTS`.
|
|
||||||
:param default_dest: If given, this should be a callable. If you call it
|
|
||||||
with the app, it should return the default upload
|
|
||||||
destination path for that app.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, name='files', extensions=DEFAULTS, default_dest=None):
|
|
||||||
if not name.isalnum():
|
|
||||||
raise ValueError("Name must be alphanumeric (no underscores)")
|
|
||||||
self.name = name
|
|
||||||
self.extensions = extensions
|
|
||||||
self._config = None
|
|
||||||
self.default_dest = default_dest
|
|
||||||
|
|
||||||
@property
|
|
||||||
def config(self):
|
|
||||||
"""
|
|
||||||
This gets the current configuration. By default, it looks up the
|
|
||||||
current application and gets the configuration from there. But if you
|
|
||||||
don't want to go to the full effort of setting an application, or it's
|
|
||||||
otherwise outside of a request context, set the `_config` attribute to
|
|
||||||
an `UploadConfiguration` instance, then set it back to `None` when
|
|
||||||
you're done.
|
|
||||||
"""
|
|
||||||
if self._config is not None:
|
|
||||||
return self._config
|
|
||||||
try:
|
|
||||||
return current_app.upload_set_config[self.name]
|
|
||||||
except AttributeError:
|
|
||||||
raise RuntimeError("cannot access configuration outside request")
|
|
||||||
|
|
||||||
def url(self, filename):
|
|
||||||
"""
|
|
||||||
This function gets the URL a file uploaded to this set would be
|
|
||||||
accessed at. It doesn't check whether said file exists.
|
|
||||||
|
|
||||||
:param filename: The filename to return the URL for.
|
|
||||||
"""
|
|
||||||
base = self.config.base_url
|
|
||||||
if base is None:
|
|
||||||
return url_for('_uploads.uploaded_file', setname=self.name,
|
|
||||||
filename=filename, _external=True)
|
|
||||||
else:
|
|
||||||
return base + filename
|
|
||||||
|
|
||||||
def path(self, filename, folder=None):
|
|
||||||
"""
|
|
||||||
This returns the absolute path of a file uploaded to this set. It
|
|
||||||
doesn't actually check whether said file exists.
|
|
||||||
|
|
||||||
:param filename: The filename to return the path for.
|
|
||||||
:param folder: The subfolder within the upload set previously used
|
|
||||||
to save to.
|
|
||||||
"""
|
|
||||||
if folder is not None:
|
|
||||||
target_folder = os.path.join(self.config.destination, folder)
|
|
||||||
else:
|
|
||||||
target_folder = self.config.destination
|
|
||||||
return os.path.join(target_folder, filename)
|
|
||||||
|
|
||||||
def file_allowed(self, storage, basename):
|
|
||||||
"""
|
|
||||||
This tells whether a file is allowed. It should return `True` if the
|
|
||||||
given `werkzeug.FileStorage` object can be saved with the given
|
|
||||||
basename, and `False` if it can't. The default implementation just
|
|
||||||
checks the extension, so you can override this if you want.
|
|
||||||
|
|
||||||
:param storage: The `werkzeug.FileStorage` to check.
|
|
||||||
:param basename: The basename it will be saved under.
|
|
||||||
"""
|
|
||||||
return self.extension_allowed(extension(basename))
|
|
||||||
|
|
||||||
def extension_allowed(self, ext):
|
|
||||||
"""
|
|
||||||
This determines whether a specific extension is allowed. It is called
|
|
||||||
by `file_allowed`, so if you override that but still want to check
|
|
||||||
extensions, call back into this.
|
|
||||||
|
|
||||||
:param ext: The extension to check, without the dot.
|
|
||||||
"""
|
|
||||||
return ((ext in self.config.allow) or
|
|
||||||
(ext in self.extensions and ext not in self.config.deny))
|
|
||||||
|
|
||||||
def get_basename(self, filename):
|
|
||||||
return lowercase_ext(secure_filename(filename))
|
|
||||||
|
|
||||||
def save(self, storage, folder=None, name=None):
|
|
||||||
"""
|
|
||||||
This saves a `werkzeug.FileStorage` into this upload set. If the
|
|
||||||
upload is not allowed, an `UploadNotAllowed` error will be raised.
|
|
||||||
Otherwise, the file will be saved and its name (including the folder)
|
|
||||||
will be returned.
|
|
||||||
|
|
||||||
:param storage: The uploaded file to save.
|
|
||||||
:param folder: The subfolder within the upload set to save to.
|
|
||||||
:param name: The name to save the file as. If it ends with a dot, the
|
|
||||||
file's extension will be appended to the end. (If you
|
|
||||||
are using `name`, you can include the folder in the
|
|
||||||
`name` instead of explicitly using `folder`, i.e.
|
|
||||||
``uset.save(file, name="someguy/photo_123.")``
|
|
||||||
"""
|
|
||||||
if not isinstance(storage, FileStorage):
|
|
||||||
raise TypeError("storage must be a werkzeug.FileStorage")
|
|
||||||
|
|
||||||
if folder is None and name is not None and "/" in name:
|
|
||||||
folder, name = os.path.split(name)
|
|
||||||
|
|
||||||
basename = self.get_basename(storage.filename)
|
|
||||||
if name:
|
|
||||||
if name.endswith('.'):
|
|
||||||
basename = name + extension(basename)
|
|
||||||
else:
|
|
||||||
basename = name
|
|
||||||
|
|
||||||
if not self.file_allowed(storage, basename):
|
|
||||||
raise UploadNotAllowed()
|
|
||||||
|
|
||||||
if folder:
|
|
||||||
target_folder = os.path.join(self.config.destination, folder)
|
|
||||||
else:
|
|
||||||
target_folder = self.config.destination
|
|
||||||
if not os.path.exists(target_folder):
|
|
||||||
os.makedirs(target_folder)
|
|
||||||
if os.path.exists(os.path.join(target_folder, basename)):
|
|
||||||
basename = self.resolve_conflict(target_folder, basename)
|
|
||||||
|
|
||||||
target = os.path.join(target_folder, basename)
|
|
||||||
storage.save(target)
|
|
||||||
if folder:
|
|
||||||
return posixpath.join(folder, basename)
|
|
||||||
else:
|
|
||||||
return basename
|
|
||||||
|
|
||||||
def resolve_conflict(self, target_folder, basename):
|
|
||||||
"""
|
|
||||||
If a file with the selected name already exists in the target folder,
|
|
||||||
this method is called to resolve the conflict. It should return a new
|
|
||||||
basename for the file.
|
|
||||||
|
|
||||||
The default implementation splits the name and extension and adds a
|
|
||||||
suffix to the name consisting of an underscore and a number, and tries
|
|
||||||
that until it finds one that doesn't exist.
|
|
||||||
|
|
||||||
:param target_folder: The absolute path to the target.
|
|
||||||
:param basename: The file's original basename.
|
|
||||||
"""
|
|
||||||
name, ext = os.path.splitext(basename)
|
|
||||||
count = 0
|
|
||||||
while True:
|
|
||||||
count = count + 1
|
|
||||||
newname = '%s_%d%s' % (name, count, ext)
|
|
||||||
if not os.path.exists(os.path.join(target_folder, newname)):
|
|
||||||
return newname
|
|
||||||
|
|
||||||
|
|
||||||
uploads_mod = Blueprint('_uploads', __name__, url_prefix='/_uploads')
|
|
||||||
|
|
||||||
|
|
||||||
@uploads_mod.route('/<setname>/<path:filename>')
|
|
||||||
def uploaded_file(setname, filename):
|
|
||||||
config = current_app.upload_set_config.get(setname)
|
|
||||||
if config is None:
|
|
||||||
abort(404)
|
|
||||||
return send_from_directory(config.destination, filename)
|
|
||||||
|
|
||||||
|
|
||||||
class TestingFileStorage(FileStorage):
|
|
||||||
"""
|
|
||||||
This is a helper for testing upload behavior in your application. You
|
|
||||||
can manually create it, and its save method is overloaded to set `saved`
|
|
||||||
to the name of the file it was saved to. All of these parameters are
|
|
||||||
optional, so only bother setting the ones relevant to your application.
|
|
||||||
|
|
||||||
:param stream: A stream. The default is an empty stream.
|
|
||||||
:param filename: The filename uploaded from the client. The default is the
|
|
||||||
stream's name.
|
|
||||||
:param name: The name of the form field it was loaded from. The default is
|
|
||||||
`None`.
|
|
||||||
:param content_type: The content type it was uploaded as. The default is
|
|
||||||
``application/octet-stream``.
|
|
||||||
:param content_length: How long it is. The default is -1.
|
|
||||||
:param headers: Multipart headers as a `werkzeug.Headers`. The default is
|
|
||||||
`None`.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, stream=None, filename=None, name=None,
|
|
||||||
content_type='application/octet-stream', content_length=-1,
|
|
||||||
headers=None):
|
|
||||||
FileStorage.__init__(self, stream, filename, name=name,
|
|
||||||
content_type=content_type, content_length=content_length,
|
|
||||||
headers=None)
|
|
||||||
self.saved = None
|
|
||||||
|
|
||||||
def save(self, dst, buffer_size=16384):
|
|
||||||
"""
|
|
||||||
This marks the file as saved by setting the `saved` attribute to the
|
|
||||||
name of the file it was saved to.
|
|
||||||
|
|
||||||
:param dst: The file to save to.
|
|
||||||
:param buffer_size: Ignored.
|
|
||||||
"""
|
|
||||||
if isinstance(dst, string_types):
|
|
||||||
self.saved = dst
|
|
||||||
else:
|
|
||||||
self.saved = dst.name
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
from captcha.image import ImageCaptcha
|
|
||||||
from io import BytesIO
|
|
||||||
from PIL import Image
|
|
||||||
from random import choices
|
|
||||||
|
|
||||||
from flask import session, make_response
|
|
||||||
from flask_login import current_user
|
|
||||||
|
|
||||||
|
|
||||||
def gen_captcha(content='0123456789'):
|
|
||||||
""" 生成验证码 """
|
|
||||||
image = ImageCaptcha()
|
|
||||||
# 获取字符串
|
|
||||||
captcha_text = "".join(choices(content, k=4))
|
|
||||||
# 生成图像
|
|
||||||
captcha_image = Image.open(image.generate(captcha_text))
|
|
||||||
return captcha_text, captcha_image
|
|
||||||
|
|
||||||
|
|
||||||
# 生成验证码
|
|
||||||
def get_captcha_image():
|
|
||||||
code, image = gen_captcha()
|
|
||||||
out = BytesIO()
|
|
||||||
session["code"] = code
|
|
||||||
image.save(out, 'png')
|
|
||||||
out.seek(0)
|
|
||||||
resp = make_response(out.read())
|
|
||||||
resp.content_type = 'image/png'
|
|
||||||
return resp, code
|
|
||||||
|
|
||||||
|
|
||||||
# 授权路由存入session
|
|
||||||
def add_auth_session():
|
|
||||||
role = current_user.role
|
|
||||||
user_power = []
|
|
||||||
for i in role:
|
|
||||||
if i.enable == 0:
|
|
||||||
continue
|
|
||||||
for p in i.power:
|
|
||||||
if p.enable == 0:
|
|
||||||
continue
|
|
||||||
user_power.append(p.code)
|
|
||||||
session['permissions'] = user_power
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
import typing as t
|
|
||||||
|
|
||||||
|
|
||||||
def success_api(message: str = "成功", code: int = 200) -> t.Dict:
|
|
||||||
""" 成功响应 默认值”成功“ """
|
|
||||||
return {'success': True, 'message': message, 'code': code}
|
|
||||||
|
|
||||||
|
|
||||||
def fail_api(message: str = "失败", code: int = 404) -> t.Dict:
|
|
||||||
""" 失败响应 默认值“失败” """
|
|
||||||
return {'success': False, 'message': message, 'code': code}
|
|
||||||
|
|
||||||
|
|
||||||
def table_api(success: bool = True,
|
|
||||||
message: str = "",
|
|
||||||
result: t.Union[dict, list] = None,
|
|
||||||
code: int = 0) -> t.Dict:
|
|
||||||
"""
|
|
||||||
动态表格渲染响应
|
|
||||||
此方法返回数据给前端
|
|
||||||
{
|
|
||||||
'success': True,
|
|
||||||
'code': 10002,
|
|
||||||
'message': '提示消息',
|
|
||||||
'result':{'items':[],'total': 100}
|
|
||||||
}
|
|
||||||
|
|
||||||
注:lay_ui 表格数据需要指定 code=0
|
|
||||||
"""
|
|
||||||
return {
|
|
||||||
'success': success,
|
|
||||||
'message': message,
|
|
||||||
'code': code,
|
|
||||||
'result': result,
|
|
||||||
}
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
import typing as t
|
|
||||||
from functools import wraps
|
|
||||||
|
|
||||||
from flask import abort, request, jsonify, session
|
|
||||||
from flask_login import login_required
|
|
||||||
from flask_login import current_user
|
|
||||||
|
|
||||||
from extensions import db
|
|
||||||
from models import LogModel
|
|
||||||
|
|
||||||
|
|
||||||
def record_logging(success: bool = True) -> None:
|
|
||||||
"""
|
|
||||||
记录用户日志数据
|
|
||||||
"""
|
|
||||||
info = {
|
|
||||||
'method': request.method,
|
|
||||||
'url': request.path,
|
|
||||||
'ip': request.remote_addr,
|
|
||||||
'user_agent': request.headers.get('User-Agent'),
|
|
||||||
'desc': str(dict(request.values)),
|
|
||||||
'uid': current_user.id,
|
|
||||||
'success': success
|
|
||||||
}
|
|
||||||
log = LogModel()
|
|
||||||
for key, value in info.items():
|
|
||||||
setattr(log, key, value)
|
|
||||||
|
|
||||||
db.session.add(log)
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
|
|
||||||
def view_logging_required(func: t.Callable) -> t.Callable:
|
|
||||||
"""
|
|
||||||
日志装饰器,用于记录请求
|
|
||||||
"""
|
|
||||||
|
|
||||||
@wraps(func)
|
|
||||||
def wrapper(*args, **kwargs) -> t.Callable:
|
|
||||||
record_logging()
|
|
||||||
return func(*args, **kwargs)
|
|
||||||
|
|
||||||
return wrapper
|
|
||||||
|
|
||||||
|
|
||||||
def permission_required(permission: str) -> t.Callable:
|
|
||||||
"""
|
|
||||||
权限装饰器,用于过滤需要的权限
|
|
||||||
"""
|
|
||||||
|
|
||||||
def decorator(func: t.Callable):
|
|
||||||
@wraps(func)
|
|
||||||
def wrapper(*args, **kwargs) -> t.Callable:
|
|
||||||
if permission not in session.get('permissions'):
|
|
||||||
record_logging(success=False)
|
|
||||||
abort(403)
|
|
||||||
return func(*args, **kwargs)
|
|
||||||
|
|
||||||
return wrapper
|
|
||||||
|
|
||||||
return decorator
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
import os
|
|
||||||
|
|
||||||
from flask import current_app
|
|
||||||
|
|
||||||
from common.flask_uploads import UploadSet, IMAGES
|
|
||||||
from extensions import db
|
|
||||||
from models import PhotoModel
|
|
||||||
|
|
||||||
photos = UploadSet('photos', IMAGES)
|
|
||||||
|
|
||||||
|
|
||||||
def upload_one(photo, mime):
|
|
||||||
filename = photos.save(photo)
|
|
||||||
file_url = photos.url(filename)
|
|
||||||
|
|
||||||
upload_url = current_app.config.get("UPLOADED_PHOTOS_DEST")
|
|
||||||
size = os.path.getsize(upload_url + '/' + filename)
|
|
||||||
photo = PhotoModel(name=filename, href=file_url, mime=mime, size=size)
|
|
||||||
db.session.add(photo)
|
|
||||||
db.session.commit()
|
|
||||||
return file_url
|
|
||||||
|
|
||||||
|
|
||||||
def delete_photo_by_id(_id):
|
|
||||||
photo_name = PhotoModel.query.filter_by(id=_id).first().name
|
|
||||||
photo = PhotoModel.query.filter_by(id=_id).delete()
|
|
||||||
db.session.commit()
|
|
||||||
upload_url = current_app.config.get("UPLOADED_PHOTOS_DEST")
|
|
||||||
os.remove(upload_url + '/' + photo_name)
|
|
||||||
return photo
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
import logging
|
|
||||||
import os
|
|
||||||
|
|
||||||
# 主题面板的链接列表配置
|
|
||||||
SYSTEM_NAME = "Pear Admin"
|
|
||||||
SYSTEM_PANEL_LINKS = [
|
|
||||||
{
|
|
||||||
"icon": "layui-icon layui-icon-auz",
|
|
||||||
"title": "官方网站",
|
|
||||||
"href": "http://www.pearadmin.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"icon": "layui-icon layui-icon-auz",
|
|
||||||
"title": "开发文档",
|
|
||||||
"href": "http://www.pearadmin.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"icon": "layui-icon layui-icon-auz",
|
|
||||||
"title": "开源地址",
|
|
||||||
"href": "https://gitee.com/Jmysy/Pear-Admin-Layui"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
SECRET_KEY = os.getenv('SECRET_KEY', 'dev key')
|
|
||||||
|
|
||||||
# mysql 配置
|
|
||||||
MYSQL_USERNAME = "root"
|
|
||||||
MYSQL_PASSWORD = "123456"
|
|
||||||
MYSQL_HOST = "127.0.0.1"
|
|
||||||
MYSQL_PORT = 3306
|
|
||||||
MYSQL_DATABASE = "PearAdminFlask"
|
|
||||||
|
|
||||||
# redis 配置
|
|
||||||
REDIS_HOST = "127.0.0.1"
|
|
||||||
REDIS_PORT = 6379
|
|
||||||
|
|
||||||
""" Sqlalchemy 配置 """
|
|
||||||
SQLALCHEMY_DATABASE_URI = r'sqlite:///pear_admin.db'
|
|
||||||
SQLALCHEMY_TRACK_MODIFICATIONS = True
|
|
||||||
SQLALCHEMY_ECHO = False
|
|
||||||
SQLALCHEMY_POOL_RECYCLE = 8
|
|
||||||
# SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{MYSQL_USERNAME}:{MYSQL_PASSWORD}@\
|
|
||||||
# {MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DATABASE}"
|
|
||||||
|
|
||||||
LOG_LEVEL = logging.ERROR
|
|
||||||
|
|
||||||
# 图片文件存放位置
|
|
||||||
UPLOADED_PHOTOS_DEST = os.path.join(os.path.dirname(os.path.abspath(__name__)), 'static', 'upload')
|
|
||||||
UPLOADED_FILES_ALLOW = ['gif', 'jpg']
|
|
||||||
# JSON配置
|
|
||||||
JSON_AS_ASCII = False
|
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
version: '3'
|
||||||
|
services:
|
||||||
|
flask:
|
||||||
|
build: .
|
||||||
|
ports:
|
||||||
|
- "8000:8000"
|
||||||
|
restart: always
|
||||||
|
links:
|
||||||
|
- mysql:dbserver
|
||||||
|
mysql:
|
||||||
|
image: "mysql:5.7"
|
||||||
|
environment:
|
||||||
|
- MYSQL_ROOT_PASSWORD=root
|
||||||
|
restart: always
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
from flask import Flask
|
|
||||||
|
|
||||||
from .init_databases import register_script
|
|
||||||
from .init_sqlalchemy import db, init_databases
|
|
||||||
from .init_login import init_login_manager
|
|
||||||
from .init_template_directives import init_template_directives
|
|
||||||
from .init_error_views import init_error_views
|
|
||||||
|
|
||||||
|
|
||||||
def init_plugs(app: Flask) -> None:
|
|
||||||
init_login_manager(app)
|
|
||||||
init_databases(app)
|
|
||||||
init_template_directives(app)
|
|
||||||
init_error_views(app)
|
|
||||||
|
|
||||||
# 生成测试数据的命令,生成环境可以注释
|
|
||||||
register_script(app)
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
from flask import Flask
|
|
||||||
import re
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
date_str = re.compile('\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d$')
|
|
||||||
|
|
||||||
|
|
||||||
def add_data(data_list, obj):
|
|
||||||
from extensions import db
|
|
||||||
|
|
||||||
for _data in data_list:
|
|
||||||
dept = obj()
|
|
||||||
for key, value in _data.items():
|
|
||||||
|
|
||||||
if isinstance(value, str) and date_str.match(value):
|
|
||||||
value = datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
|
|
||||||
|
|
||||||
setattr(dept, key, value)
|
|
||||||
db.session.add(dept)
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
|
|
||||||
def register_script(app: Flask):
|
|
||||||
@app.cli.command()
|
|
||||||
def init_db():
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
|
|
||||||
path = os.path.dirname(os.path.abspath(__name__))
|
|
||||||
path = os.path.join(path, 'static', 'data')
|
|
||||||
cp_dept_data_list = json.loads(open(os.path.join(path, 'cp_dept.json'), encoding='utf-8').read())
|
|
||||||
cp_user_data_list = json.loads(open(os.path.join(path, 'cp_user.json'), encoding='utf-8').read())
|
|
||||||
file_photo_data_list = json.loads(open(os.path.join(path, 'file_photo.json'), encoding='utf-8').read())
|
|
||||||
rt_power_data_list = json.loads(open(os.path.join(path, 'rt_power.json'), encoding='utf-8').read())
|
|
||||||
rt_role_data_list = json.loads(open(os.path.join(path, 'rt_role.json'), encoding='utf-8').read())
|
|
||||||
rt_role_power_data_list = json.loads(open(os.path.join(path, 'rt_role_power.json'), encoding='utf-8').read())
|
|
||||||
rt_user_role_data_list = json.loads(open(os.path.join(path, 'rt_user_role.json'), encoding='utf-8').read())
|
|
||||||
|
|
||||||
"""数据库初始化"""
|
|
||||||
|
|
||||||
# 创建化部门数据
|
|
||||||
from models import DepartmentModel
|
|
||||||
add_data(cp_dept_data_list, DepartmentModel)
|
|
||||||
|
|
||||||
# 图片数据
|
|
||||||
from models import PhotoModel
|
|
||||||
|
|
||||||
add_data(file_photo_data_list, PhotoModel)
|
|
||||||
|
|
||||||
# 初始化权限表数据
|
|
||||||
from models import RightModel
|
|
||||||
|
|
||||||
add_data(rt_power_data_list, RightModel)
|
|
||||||
# 初始化角色表
|
|
||||||
from models import RoleModel
|
|
||||||
|
|
||||||
# 角色权限关系表
|
|
||||||
from extensions import db
|
|
||||||
for data in rt_role_power_data_list:
|
|
||||||
db.session.execute('insert into rt_role_power VALUES (%s, %s, %s);' % tuple(data))
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
add_data(rt_role_data_list, RoleModel)
|
|
||||||
|
|
||||||
# 管理员用户
|
|
||||||
from models import UserModel
|
|
||||||
|
|
||||||
add_data(cp_user_data_list, UserModel)
|
|
||||||
|
|
||||||
# 用户角色表
|
|
||||||
from extensions import db
|
|
||||||
|
|
||||||
for data in rt_user_role_data_list:
|
|
||||||
db.session.execute('insert into rt_user_role VALUES (%s, %s, %s);' % tuple(data))
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
@app.cli.command()
|
|
||||||
def turn():
|
|
||||||
"""清空数据库"""
|
|
||||||
from extensions import db
|
|
||||||
db.drop_all()
|
|
||||||
db.create_all()
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user