from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
from exts import db app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:Password@hostip:5432/postgres' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config["SQLALCHEMY_ECHO"] = True db.init_app(app)
from exts import db class Books(db.Model): __tablename__ = 'books' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) author = db.Column(db.String(64), nullable=False) category = db.Column(db.String(64), nullable=False) def __repr__(self): return '<Book %r>' % self.name
from exts import db from models import Books db.create_all()
python create_db.py
, 在数据库中创建数据表app.py
import json from models import * from flask import Flask from flask_cors import * from exts import db app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:Password@hostip:5432/postgres' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config["SQLALCHEMY_ECHO"] = True db.init_app(app) CORS(app, resources=r'/*') def query2dict(model_list): if isinstance(model_list, list): if isinstance(model_list[0], db.Model): lst = [] for model in model_list: dic = {} for col in model.__table__.columns: dic[col.name] = getattr(model, col.name) lst.append(dic) return lst else: lst = [] for result in model_list: lst.append([dict(zip(result.keys, r)) for r in result]) return lst else: if isinstance(model_list, db.Model): dic = {} for col in model_list.__table__.columns: dic[col.name] = getattr(model_list, col.name) return dic else: return dict(zip(model_list.keys(), model_list)) @app.route('/', methods=["POST"]) def query_books(): books = Books.query.all() books = query2dict(books) return json.dumps(books)
index.vue
<template> <div> <div> <el-row> <el-button type="primary" icon="el-icon-edit" circle /> <el-button type="primary" icon="el-icon-delete" circle /> <el-button type="primary" icon="el-icon-document-add" circle /> </el-row> </div> <div> <el-table :key="itemKey" :data="tableData" :header-cell-style="{background:'#eef1f6',color:'#606266'}" border :row-style="{height: '50px'}" @selection-change="handleSelectionChange" > <el-table-column type="selection" width="40" /> <el-table-column prop="id" label="ID" align="center" /> <el-table-column prop="name" label="Name" align="center" /> <el-table-column prop="author" label="Author" align="center" /> <el-table-column prop="category" label="Category" align="center" /> </el-table> </div> </div> </template> <script> export default { data () { return { itemKey: 0, tableData: [], selectData: [] } }, created () { this.getData() }, methods: { getData () { this.axios.post( 'http://127.0.0.1:5000/' ).then(res => { const data = res.data data.forEach((item) => { this.tableData.push(item) this.itemKey = Math.random() }) }) }, handleSelectionChange (val) { this.selectedData = val } } } </script>
效果