Flask-SQLAlchemy初探
连接数据库
SQLAlchemy有多种连接数据库的方式,这里先写一下sqlite这种方式,后续用到其他的方式的时候再补充。
为了以后复制粘贴就可以用,这里贴全点
#coding:utf-8
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
import os
basedir = os.path.abspath(os.path.dirname(__file__)) #获取当前文件的目录
app = Flask(__name__)
app.config['SECRET_KEY'] = 'zheshiyigekey'
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///' + os.path.join(basedir, 'data2.sqlite') #sqlite的链接方式
#注意这里要写绝对路径sqlite:///这是sqlite的标识,后边跟绝对路径,比如上面的转换为绝对路径如下
#app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:////tmp/data2.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True #自动提交事务
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True #一个异常提示,配置为True后不在提示警告信息
db = SQLAlchemy(app)
建立映射关系
class Article(db.Model): #db.Model继承SQLAlchemy的类
__tablename__='article' #可不定义,默认为类名称的全小写,不过为了代码可读建议写
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
title = db.Column(db.String(64),nullable=False)
content = db.Column(db.String,nullable=False)
#Integer == int
#primary_key == 主键
#autoincrement == 自增
#String == char
#nullable == 是否允许为空
#定义repr决定了查询的时候展示什么,如果未定义则返回为query状态
#如下定义后的返回结果为[<1,aaa,bbb>, <2,ccc,ddd>]
#无定义的返回结果为[<Article 1>, <Article 2>]
def __repr__(self):
return "<%s,%s,%s>"%(self.id,self.title,self.content)
初始化表结构,删除表结构
db.drop_all()
db.create_all() #如果表结构已经定义完成,修改映射关系后执行此命令无效,需要执行删除表结构后才可以重新定义,如果不删除
#表结构,则需要做数据库迁移,后续研究后再发出
增删改查
@app.route('/inster/')
def inster():
#inster
article1 = Article(title='aaa',content='bbb')
article2 = Article(title='ccc', content='ddd')
db.session.add(article1)
db.session.add(article2)
db.session.commit()
return 'inster'
@app.route('/select/')
def select():
#select
# result = Article.query.filter(Article.title == 'aaa').all() #查询所有符合条件的数据
result = Article.query.all()
# result = Article.query.filter(Article.title == 'aaa').first() #查询符合条件的第一条数据,如果没有数据则返回None
#如果未定义repr用这个输出
# for i in result:
# print i.id
# print i.title
# print i.content
#定义了repr则可以直接输出
print result
return 'select'
@app.route('/update/')
def update():
#update
article1 = Article.query.filter(Article.title == 'aaa').first()
article1.title = 'new title'
db.session.commit()
return "update"
@app.route('/delete/')
def delete():
#delete
article1 = Article.query.filter(Article.title == 'aaa').first()
db.session.delete(article1)
db.session.commit()
return "delete"
#测试的时候注意执行顺序 先插入,再查询,再更新或者删除,再查询
最后贴一份全的代码
#coding:utf-8
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
import os
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SECRET_KEY'] = 'zheshiyigekey'
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///' + os.path.join(basedir, 'data2.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True
db = SQLAlchemy(app)
class Article(db.Model):
__tablename__='article'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
title = db.Column(db.String(64),nullable=False)
content = db.Column(db.String,nullable=False)
# def __repr__(self):
# return "<%s,%s,%s>"%(self.id,self.title,self.content)
db.drop_all()
db.create_all()
@app.route('/inster/')
def inster():
#inster
article1 = Article(title='aaa',content='bbb')
article2 = Article(title='ccc', content='ddd')
db.session.add(article1)
db.session.add(article2)
db.session.commit()
return 'inster'
@app.route('/select/')
def select():
#select
# result = Article.query.filter(Article.title == 'aaa').all() #查询所有符合条件的数据
result = Article.query.all()
# result = Article.query.filter(Article.title == 'aaa').first() #查询符合条件的第一条数据,如果没有数据则返回None
# for i in result:
# print i.id
# print i.title
# print i.content
print result
return 'select'
@app.route('/update/')
def update():
#update
article1 = Article.query.filter(Article.title == 'aaa').first()
print article1
print article1.title
article1.title = 'new title'
db.session.commit()
return "update"
@app.route('/delete/')
def delete():
#delete
article1 = Article.query.filter(Article.title == 'aaa').first()
db.session.delete(article1)
db.session.commit()
return "delete"
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000, debug=True)
网友评论