Flask + Vue的一个示例
这里记录下一个Flask+Vue的一个示例
1.系统环境:Python3.7
sqlite3数据库,数据库名称:books.db
2.项目结构
3.app.py
import sqlite3 from flask import Flask from flask import jsonify,render_template app = Flask(__name__) @app.route("/") def home(): return render_template("index.html",title='测试') @app.route("/api/books") def books(): conn = sqlite3.connect("books.db") conn.row_factory = sqlite3.Row cur = conn.cursor() sql = "Select * from books" rows = cur.execute(sql).fetchall() rows = [dict(row) for row in rows] return jsonify(rows)
4.index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>Flask Vue</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script> </head> <body> <div id="app"> <h1>Flask & Vue.js {{ title }}</h1> <table border="1" cellpadding=5 cellspacing=5> <tr> <td>ID</td> <td>标题</td> <td>作者</td> <td>定价</td> </tr> <tr v-for="book in books"> <td>[[book.id]]</td> <td>[[book.title]]</td> <td>[[book.author]]</td> <td>[[book.price]]</td> </tr> </table> <script> var app= new Vue({ el: "#app", data:{ books:[] }, delimiters:["[[","]]"], mounted:function(){ this.fetchData(); }, methods:{ fetchData(){ this.$http.get("/api/books").then(rsp=>{ this.books=rsp.body },err=>{console.log('Error')}); } } }) </script> </div> </body> </html>
5.构造数据库语句
1.创建数据库 sqlite3 books.db 2.创建表 create table books(id int PRIMARY Key not null,title Text not null,author Text not null,price real not null); 3.插入记录 insert into books values(1,'Python','Eason',39.0); insert into books values(2,'django','Eason',99.0); insert into books values(3,'flask','Eason',129.0); insert into books values(4,'Vuejs','Eason',50.0);
6.示例效果
1).
2).
幸福都是奋斗出来的,努力奋斗才能梦想成真。坚持自律,约束自我,克制弱点,坚持努力,遇见更好的自己。