赞
踩
SQLAlchemy初始化和数据库连接:
这个配置比较多,因为不像狗书和狼书中,使用的是sqlite3,更轻量级配置简单;这个教程使用的是mysql所以需要配置mysql的账户密码等等信息,就像pymysql一样。
1.初始化和设置数据库配置信息:
使用flask_sqlalchemy中SQLAlchemy进行初始化:
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
2.设置配置信息:在config.py文件中添加以下配置信息:
DIALECT = 'mysql'
DRIVER = 'mysqldb'
USERNAME = 'root'
PASSWORD = '000220'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'db_demo1'
SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT, DRIVER, USERNAME, PASSWORD,HOST, PORT, DATABASE)
SQLALCHEMY_TRACK_MODIFICATIONS = False
3.在主app文件中,添加配置文件:
app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)
使用Flask—Alchemy创建模型与表的映射:
1.模型需要继承自db.Model,然需要映射到表中的属性,必须写成db.Column的数据类型。
2.数据类型:
db.Integer代表的是整型,
db.String代表的是varchar,需要指定最长的长度
db.Text代表的是text,
3.其他参数:
primary_key:将此字段设置为主键。
autoincrement:将此主键设为自增长。
nullable:默认为True,可以为空;False不可为空。
4.最后调用db.create_all()将模型真正创建在数据库中。
# article表: # create table article( # id int primary key autoincrement, # title varchar(100) not null, # content text not null. # ) class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) db.create_all()
Flask-SQLAlchemy数据的增删改查:
1.增:
# 增加:
article1 = Article(title='aaa', content='bbb')
db.session.add(article1)
# 事务:
db.session.commit()
2.查:
# 查
# select * from article where title='aaa'
result = Article.query.filter(Article.title == 'aaa').all()
article1 = result[0]
print(article1.title)
print(article1.content)
3.改:
# 改
# 1.先查找出要更改的数据
article1 = Article.query.filter(Article.title == 'aaa').first()
# 2.修改数据
article1.title = 'new title'
# 3.事务提交
db.session.commit()
4.删
# 删
# 1.查找出需要删除的数据
article1 = Article.query.filter(Article.content == 'bbb').first()
# 2.删除数据
db.session.delete(article1)
# 3. 事务提交
db.session.commit()
整体代码:
config.py
DIALECT = 'mysql'
DRIVER = 'mysqldb'
USERNAME = 'root'
PASSWORD = '000220'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'db_demo1'
SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT, DRIVER, USERNAME, PASSWORD,HOST, PORT, DATABASE)
SQLALCHEMY_TRACK_MODIFICATIONS = False
app.py
from flask import Flask from flask_sqlalchemy import SQLAlchemy import config app = Flask(__name__) app.config.from_object(config) db = SQLAlchemy(app) # article表: # create table article( # id int primary key autoincrement, # title varchar(100) not null, # content text not null. # ) class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) db.create_all() @app.route('/') def index(): # 增加: article1 = Article(title='aaa', content='bbb') db.session.add(article1) # 事务: db.session.commit() # 查 # select * from article where title='aaa' result = Article.query.filter(Article.title == 'aaa').all() article1 = result[0] print(article1.title) print(article1.content) # 改 # 1.先查找出要更改的数据 article1 = Article.query.filter(Article.title == 'aaa').first() # 2.修改数据 article1.title = 'new title' # 3.事务提交 db.session.commit() # 删 # 1.查找出需要删除的数据 article1 = Article.query.filter(Article.content == 'bbb').first() # 2.删除数据 db.session.delete(article1) # 3. 事务提交 db.session.commit() return 'index' if __name__ == '__main__': app.run()
Flask-SQLAlchemy外键和关系映射:
1.外键:
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(100), nullable=False)
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
author = db.relationship('User', backref=db.backref('articles'))
2.author = db.relationship(‘User’, backref=db.backref(‘articles’))解释:
给Article模型添加一个author属性,可以访问这篇文章的作者的数据,像访问普通模型一样。
backref是定义反向引用,可以通过User模型访问这个模型所写的所有文章。
全部代码:
from flask import Flask from flask_sqlalchemy import SQLAlchemy import config app = Flask(__name__) app.config.from_object(config) db = SQLAlchemy(app) # 用户表 # create table users( # id int primary_key autoincrement, # username varchar(100) not null # ) # 文章表 # create table article( # id int primary_key autoincrement, # title varchar(100) not null, # content text not null, # author_id int, # foreign_key 'author_id' references 'user.id' # ) class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(100), nullable=False) class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) author_id = db.Column(db.Integer, db.ForeignKey('user.id')) author = db.relationship('User', backref=db.backref('articles')) db.create_all() @app.route('/') def index(): # 想要添加一篇文章,因为文章必须依赖用户而存在,所以需要先添加一个用户 user1 = User(username='zl') db.session.add(user1) db.session.commit() article = Article(title='aaa', content='bbb', author_id=1) db.session.add(article) db.session.commit() # 找到文章标题为aaa的作者 article = Article.query.filter(Article.title == 'aaa').first() author_id = article.author_id user = User.query.filter(User.id == author_id).first() print(user.username) article = Article(title='aaa', content='bbb') article.author = User.query.filter(User.id==1).first() db.session.add(article) db.session.commit() # 要找到文章标题为aaa的作者 article = Article.query.filter(Article.title == 'aaa').first() print('username:%s' % article.author.username) # 要找到zl这个作者写过的所有文章 article = Article(title='111', content='222', author_id=1) db.session.add(article) db.session.commit() user = User.query.filter(User.username == 'zl').first() result = user.articles for article in result: print('-'*10) print(article.title) return 'index' if __name__ == '__main__': app.run()
多对多关系:
多对多的关系,要通过一个中间表进行关联。
中间表,不能通过class的方式实现,只能通过db.Table的方式实现
设置关联:tags = db.relationship(‘Tag’, secondary=article_tag, backref=db.backref(‘articles’)),需要使用一个关键字参数secondary=中间表来进行关联。
访问和数据添加可以通过以下方式进行操作:
article1 = Article(title='aaa') article2 = Article(title='bbb') tag1 = Tag(name='111') tag2 = Tag(name='222') article1.tags.append(tag1) article1.tags.append(tag2) article2.tags.append(tag1) article2.tags.append(tag2) db.session.add(article1) db.session.add(article2) db.session.add(tag1) db.session.add(tag2) db.session.commit()
完整代码:
from flask import Flask from flask_sqlalchemy import SQLAlchemy import config app = Flask(__name__) app.config.from_object(config) db = SQLAlchemy(app) # create table article( # id int primary key autoincrement, # title varchar(100) # ) # # create table tag( # id int primary key autoincrement, # name varchar(50) not null # ) # # create table article_tag( # article_id int, # tag_id int, # primary_key('article_id', 'tag_id'), # foreign key 'tag_id' references 'article.id', # foreign key 'article_id' references 'tag.id' # ) article_tag = db.Table('article_tag', db.Column('article_id', db.Integer, db.ForeignKey('article.id'), primary_key=True), db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True) ) class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(100), nullable=False) tags = db.relationship('Tag', secondary=article_tag, backref=db.backref('articles')) class Tag(db.Model): __tablename__ = 'tag' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(100), nullable=False) db.create_all() @app.route('/') def hello_world(): article1 = Article(title='aaa') article2 = Article(title='bbb') tag1 = Tag(name='111') tag2 = Tag(name='222') article1.tags.append(tag1) article1.tags.append(tag2) article2.tags.append(tag1) article2.tags.append(tag2) db.session.add(article1) db.session.add(article2) db.session.add(tag1) db.session.add(tag2)db.session.commit() article1 = Article.query.filter(Article.title == 'aaa').first() tags = article1.tags for tag in tags: print(tag.name) return 'Hello World!' if __name__ == '__main__': app.run(debug=True)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。