一、总体框架
二、config 配置文件
1、config.py
项目配置文件,主要存放数据库连接地址和flask端口
mysql_client = {
# ip
"host": "localhost",
# 端口
"port": 3306,
# 账号
"username": "root",
# 密码
"pwd": "12345678",
# 连接的库
"database": "database_name"
}
flask_default = {
# 端口
"port": "8079",
# ip
"host": "0.0.0.0",
"log_max": 5 * 1024 * 1024
}
2、sql_client.py
数据库连接公共类
from sqlalchemy import create_engine
from config.config import mysql_client
class MySQLLink:
def __init__(self, host=mysql_client['host'], port=mysql_client['port'], username=mysql_client['username'],
pwd=mysql_client['pwd'], database=mysql_client['database']):
self.engine = create_engine('mysql+pymysql://{}:{}@{}:{}/{}'.format(username, pwd, host, port, database))
def get_engine(self):
return self.engine
3、table.py
数据库对照表
from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, Float
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
# 用户表
class BaseData(Base):
__tablename__ = 'base'
id = Column(Integer, primary_key=True)
base_key = Column(String)
base_value = Column(String)
time = Column(DateTime, default=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
def to_dict(self):
base_data = {
'id': self.id,
'base_key': self.base_key,
'base_value': self.base_value,
'time': self.time
}
return base_data
三、model 数据库连接方法(类似于mapper)
1、添加
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from config.sql_client import MySQLLink
from config.table import BaseData
Base = declarative_base()
Session = sessionmaker(bind=MySQLLink().get_engine())
def insert(base_entity):
session = Session()
result = BaseData(
base_key=user_entity['base_key'],
base_value=user_entity['base_value'],
time=user_entity['time'])
session.add(result)
session.commit()
session.close()
return True
2、删除
# 删除数据
def remove(base_id):
session = Session()
base_to_delete = session.query(BaseData).filter_by(id=base_id).first()
if base_to_delete:
session.delete(base_to_delete)
session.commit()
session.close()
return True
3、修改
# 更新数据
def update(base_entity):
session = Session()
result = session.query(BaseData).filter_by(id=base_entity['id']).first()
if result:
for (k, v) in base_entity.items():
if k == 'base_key':
result.base_key= v
elif k == 'base_value':
result.base_value= v
elif k == 'time':
result.time= v
session.commit()
session.close()
return True
4、查询
# 通过base_type获取数据
def get_by_type(base_type):
session = Session()
result = session.query(BaseData).filter_by(base_type=base_type)
return result
四、src 核心代码块(类似于controller+service)
from flask import Blueprint, jsonify, request
import model.base_data as base_model
from utils.utils import api_result, get_success
base = Blueprint('base', __name__)
@base.route('/getByType.json', methods=['GET'])
def get_by_type():
base_type = request.args['type']
get_result = base_model.get_by_type(base_type)
result = api_result
result['data'] = [result_one.to_dict() for result_one in get_result]
result['message'] = get_success
return jsonify(result)
五、utils 工具类
1、globalVar
全局变量,类似于vuex
def _init():
global _global_dict
_global_dict = {}
def set_value(name, value):
_global_dict[name] = value
def get_value(name, defValue=None):
try:
return _global_dict[name]
except KeyError:
return defValue
2、utils.py
工具类,存放返回值实体、分页实体、常量等等,也可以单独拆分常量。
api_result = {'code': 0, 'message': '', 'data': ''}
page_data = {'pageNum': 0, 'pageSize': 0, 'data': '', 'total': 0}
get_success = '查询数据成功!'
add_success = '添加数据成功!'
update_success = '修改数据成功!'
remove_success = '删除数据成功!'
六、app.py
主程序,通过blueprint拆分接口到src,CORS防止跨域。
from flask import Flask
from flask_cors import CORS
from config.config import flask_default
from src.base_data import base
app = Flask(__name__)
app.register_blueprint(base, url_prefix='/base')
CORS(app)
if __name__ == '__main__':
app.run(host=flask_default['host'], port=flask_default['port'])