项目结构,config.py是数据库配置文件,app.py是程序入口,manage.py用于数据库映射,models.py是数据库表模型,ext.py主要是防止循环import。这里主要讲蓝图api的写法,manage.py数据库映射和config.py的设置暂时就不说了。
我在ext.py中定义了db。
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
models.py中定义了表模型。
from ext import db
class Threshold(db.Model):
__tablename__ = 'threshold'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
target_name = db.Column(db.String(20))
act_var = db.Column(db.DECIMAL(10, 4))
threshold_min = db.Column(db.DECIMAL(10, 4))
threshold_max = db.Column(db.DECIMAL(10, 4))
status = db.Column(db.String(20))
datetime = db.Column(db.DateTime)
place = db.Column(db.String(20))
蓝图query.py如下
from flask import Blueprint
from flask_restful import Api, Resource, fields, marshal_with
from ext import db
import models
query_bp = Blueprint('query', __name__, url_prefix='/query')
api = Api(query_bp)
class QueryTableView(Resource):
resource_fields = {
'id': fields.Integer,
'target_name': fields.String,
'act_var': fields.String,
'threshold_min': fields.String,
'threshold_max': fields.String,
'status': fields.String,
'datetime': fields.DateTime,
'place': fields.String
}
@marshal_with(resource_fields)
def get(self):
res = db.session.query(models.Threshold).all()
return res
api.add_resource(QueryTableView, '/table')
注意:在app.py中注册蓝图的时候要用
app.register_blueprint(query_bp)
mysql中的表
输出结果
不用考虑复杂参数化结构,表什么属性,resource_fields就设置成什么属性就行了。如果只想输出一条查询结果,改一下查询语句或者return res[0]就行,因为res是list,第一个元素是你的models类。