1.结构目录
2.创建config.py
import os
BASE_DIR = os.getcwd() # 项目的绝对路径
TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') # 模板文件的路径
STATICFILES_DIR = os.path.join(BASE_DIR, 'static') # 静态文件的路径
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost:3306/flask' # 数据库URI
SQLALCHEMY_TRACK_MODIFICATIONS = False # 查询跟踪,不太需要,False,不占用额外的内存
SQLALCHEMY_ECHO = True
2.编辑app下的__init__.py
import json
from array import array
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import SQLALCHEMY_DATABASE_URI, SQLALCHEMY_TRACK_MODIFICATIONS, SQLALCHEMY_ECHO
import datetime
from flask.json import JSONEncoder
db = SQLAlchemy()
JSONEncoder = JSONEncoder
# 自定义jsonEncode,不然返回数据库数据的时候会有报错
class CustomJSONEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S")
if isinstance(obj, bytes):
return str(obj, encoding='utf-8')
if isinstance(obj, int):
return int(obj)
elif isinstance(obj, float):
return float(obj)
elif isinstance(obj, array):
return obj.tolist()
else:
return json.JSONEncoder.default(self, obj)
def create_app():
app = Flask(__name__)
# 替换默认的json编码器
app.json_encoder = CustomJSONEncoder
app.config['SERVER_NAME'] = "127.0.0.1:8080"
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = SQLALCHEMY_TRACK_MODIFICATIONS
app.config['SQLALCHEMY_ECHO'] = SQLALCHEMY_ECHO
db.init_app(app=app)
with app.app_context():
from app.routes import base
app.register_blueprint(base)
return app
3.创建DictType db模型
from app import db
from datetime import datetime
class DictType(db.Model):
__tablename__ = 'SYS_DICT_TYPE'
dict_id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='主键')
dict_name = db.Column(db.String(100), comment='字典名称')
dict_type = db.Column(db.String(100), comment='字典类型')
status = db.Column(db.Integer, comment='字典状态')
create_by = db.Column(db.String(64), comment='创建人')
create_time = db.Column(db.DATETIME, default=datetime.now, comment='创建时间')
update_by = db.Column(db.String(64), comment='更新人')
update_time = db.Column(db.DATETIME, default=datetime.now, comment='更新时间')
remark = db.Column(db.String(500), comment='备注')
def to_json(self):
return {
'dictId': self.dict_id,
'dictName': self.dict_name,
'dictType': self.dict_type,
'status': self.status,
'createBy': self.create_by,
'createTime': self.create_time,
'updateBy': self.update_by,
'updateTime': self.update_time,
'remark': self.remark,
}
db.create_all()
在routes目录下的 init.py 创建蓝图
from flask import Blueprint
base = Blueprint('base', __name__)
from .dicttype import *
4.创建dicttype路由
from ..base import base
from ..handler import dicthandler
@base.route('/dict/type/add', methods=['POST'])
def dict_type_add():
return dicthandler.dict_type_add()
@base.route('/dict/type/edit', methods=['POST'])
def dict_type_edit():
return dicthandler.dict_type_edit()
@base.route('/dict/type/delete/<id>', methods=['GET'])
def dict_type_delete(id):
return dicthandler.dict_type_delete(id)
@base.route('/dict/type/list', methods=['GET'])
def dict_type_list():
return dicthandler.dict_type_list()
@base.route('/dict/type/detail/<id>', methods=['GET'])
def dict_type_detail(id):
return dicthandler.dict_type_detail(id)
5.创建dicthandler业务处理类
from flask import request
from app import db
from ..models import DictData, DictType
from ..respones import response as Response
import datetime
# 字典类型列表查询
def dict_type_list():
datas = DictType.DictType.query.all()
return Response.ok([DictType.DictType.to_json(data) for data in datas])
# 字典类型新增
def dict_type_add():
json = request.json
dict_name = json['dict_name']
dict_type = json['dict_type']
status = json['status']
remark = json['remark']
dictType = DictType.DictType()
dictType.dict_name = dict_name
dictType.dict_type = dict_type
dictType.status = status
dictType.remark = remark
db.session.add(dictType)
db.session.commit()
return Response.ok()
# 字典类型详情
def dict_type_detail(id):
dictType = DictType.DictType.query.get(id)
if dictType is None:
return Response.ok()
return Response.ok(DictType.DictType.to_json(dictType))
def dict_type_edit():
json = request.json
json['update_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
DictType.DictType.query.filter_by(dict_id=json['dict_id']).update(json)
db.session.commit()
return Response.ok(json)
# 字典类型删除
def dict_type_delete(id):
dictType = DictType.DictType.query.get(id)
if dictType is None:
return Response.ok({"dict_id": id})
db.session.delete(dictType)
db.session.commit()
return Response.ok({"dict_id": id})
# 字典数据列表
def dict_data_list():
data = DictData.DictData.query.all()
return Response.ok(data)
def dict_data_add():
json = request.json
dict_sort = json['dict_sort']
dict_label = json['dict_label']
dict_value = json['dict_value']
dict_id = json['dict_id']
status = json['status']
remark = json['remark']
dictData = DictData.DictData(dict_sort=dict_sort, dict_label=dict_label, dict_value=dict_value, dict_id=dict_id,
status=status, remark=remark)
db.session.add(dictData)
db.session.commit()
return Response.ok()
def query_by_dict_id():
dict_id = request.args['dictId']
dictType = DictType.DictType.query.get(dict_id)
if dictType is None:
return Response.ok()
dictData = DictData.DictData.query.filter_by(dict_id=dict_id).order_by(DictData.DictData.dict_sort).all()
data = DictData.DictData.query_dict_data(dictType, dictData)
return Response.ok(data)