往数据库中添加一张保存文章的表,表明为article,字段有id,title,content
同样一个配置文件:config.py
DEBUG = True
#dialect+driver://root:1q2w3e4r5t@127.0.0.1:3306/
DIALECT = 'mysql'
DRIVER='pymysql'
USERNAME = 'root'
PASSWORD = '1q2w3e4r5t'
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
print(SQLALCHEMY_DATABASE_URI)
flask app 中新建一个class Blog,里面定义好id ,title ,content。代码执行到db.create_all()时,会自动在数据库中创建一个表,表明为blog
from flask import Flask
import config from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.declarative import declarative_base app = Flask(__name__)
app.config.from_object(config) db = SQLAlchemy(app)
Base = declarative_base() class Blog(db.Model):
__tablename__ = 'blog'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
title = db.Column(db.String(100),nullable=False)
content = db.Column(db.Text,nullable=True) db.create_all() @app.route('/')
def index():
return 'index' if __name__ == '__main__':
app.run(debug=True)
启动flask app,数据库中查询表和表结构如下,有新增相应的表,说明新建表成功
数据库表中的数据增删改查
#新增
blog = Blog(title="first blog",content="this is my first blog")
db.session.add(blog)
db.session.commit() #查询
#res =Blog.query.filter(Blog.title=="first blog")[0] res =Blog.query.filter(Blog.title=="first blog").first()
print(res.title)
#修改
blog_edit = Blog.query.filter(Blog.title=="first blog").first()
blog_edit.title = "new first blog"
db.session.commit()
#删除
blog_delete = Blog.query.filter(Blog.title=="first blog").first()
db.session.delete(blog_delete)
db.session.commit()
完整代码
from flask import Flask
import config from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.declarative import declarative_base app = Flask(__name__)
app.config.from_object(config) db = SQLAlchemy(app)
Base = declarative_base() class Blog(db.Model):
__tablename__ = 'blog'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
title = db.Column(db.String(100),nullable=False)
content = db.Column(db.Text,nullable=True) db.create_all() @app.route('/')
def index():
#新增
blog = Blog(title="first blog",content="this is my first blog")
db.session.add(blog)
db.session.commit() #查询
#res =Blog.query.filter(Blog.title=="first blog")[0] res =Blog.query.filter(Blog.title=="first blog").first()
print(res.title)
#修改
blog_edit = Blog.query.filter(Blog.title=="first blog").first()
blog_edit.title = "new first blog"
db.session.commit()
#删除
blog_delete = Blog.query.filter(Blog.title=="first blog").first()
db.session.delete(blog_delete)
db.session.commit() return 'index' if __name__ == '__main__':
app.run(debug=True)
欢迎扫描二维码关注技术公众号:为测,上面有自动化测试方面技术文章