Javascript

flask + vue + postgres 前后端分离实例

本文主要是介绍flask + vue + postgres 前后端分离实例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

配置数据库

  • 新建exts.py import数据库
    from flask_sqlalchemy import SQLAlchemy
    
    db = SQLAlchemy()
    
  • 在app.py中配置数据库
    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)
    
  • 新建models.py, 创建数据库模型
    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
    
  • 新建create_db.py
    from exts import db
    from models import Books
    
    db.create_all()
    
  • 执行create_db.py 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>
    
  • 效果
    在这里插入图片描述

这篇关于flask + vue + postgres 前后端分离实例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!