1.在flask文件夹中新建一个models.py文件用来定义模型,内部代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| import sqlite3
def get_conn(): return sqlite3.connect("test.db")
class User(object): def __init__(self,id,name): self.id = id self.name = name
def save(self): sql = "insert into user VALUES (?,?)" conn = get_conn() cursor = conn.cursor() cursor.execute(sql,(self.id,self.name)) conn.commit() cursor.close() conn.close()
''' staticmethod相当于一个定义在类里面的函数,所以如果一个方法既不跟实例 相关也不跟特定的类相关,推荐将其定义为一个staticmethod,这样不仅使代 码一目了然,而且似的利于维护代码。 ''' @staticmethod def query(): sql = "select * from user" conn = get_conn() cursor = conn.cursor() rows = cursor.execute(sql) users = [] for row in rows: user = User(row[0],row[1]) users.append(user) conn.commit() cursor.close() conn.close() return users
def __str__(self): return 'id:{}--name:{}'.format(self.id,self.name)
|
2.在flask文件夹中新建一个manage.py文件
###(1)导入flask_script包,导入sqlite3包,导入models.py中定义的模型,导入flask中的应用,所以最终头部代码如下
1 2 3 4
| from flask_script import Manager from learn_flask_script import app import sqlite3 from models import User
|
###(2)创建数据库,代码如下
1 2 3 4 5 6 7 8 9
| @manager.command def init_db(): sql = "create table user (id INT,name TEXT)" conn = sqlite3.connect("test.db") cursor = conn.cursor() cursor.execute(sql) conn.commit() cursor.close() conn.close()
|
###(3)保存数据,代码如下
1 2 3 4
| @manager.command def save(): user = User(1,'csdn') user.save()
|
###(4)查询数据,代码如下
1 2 3 4 5
| @manager.command def query_all(): users = User.query() for user in users: print(user)
|
整体代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| from flask_script import Manager from learn_flask_script import app import sqlite3 from models import User
manager = Manager(app)
@manager.command def init_db(): sql = "create table user (id INT,name TEXT)" conn = sqlite3.connect("test.db") cursor = conn.cursor() cursor.execute(sql) conn.commit() cursor.close() conn.close()
@manager.command def save(): user = User(1,'zhangjia') user.save()
@manager.command def query_all(): users = User.query() for user in users: print(user)
if __name__ == "__main__": manager.run()
|
3.在终端中使用命令即可运行数据库的创建,添加以及查询