flask的图书作者案例
pyhton manage.py runserver -h 0.0.0.0 -p 8888
#_*_ encoding: utf-8 _*_ @author: ty hery 2019/12/20
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, EqualTo
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
app = Flask(__name__)
app.config["SECRET_KEY"] = "12345678"
class Config(object):
'''配置参数'''
DEBUG = True
# sqlalchemy的配置参数
SQLALCHEMY_DATABASE_URI = "mysql://root:666@localhost:3306/s2"
# 设置sqlalchemy自动跟踪数据库
SQLALCHEMY_TRACK_MODIFICATIONS = True
# 查询时会显示原始SQL语句
app.config['SQLCHEMY_ECHO'] = True
app.config.from_object(Config)
db = SQLAlchemy(app)
# 创建 flask脚本管理工具对象
manager = Manager(app)
# 创建数据库迁移工具对象
Migrate(app,db)
# 向manager对象中添加数据库的操作命令
manager.add_command("db",MigrateCommand)
class Author(db.Model):
'''作者'''
__tablename__='tbl_authors'
id = db.Column(db.SmallInteger, primary_key=True)
name = db.Column(db.String(8),unique=True)
email = db.Column(db.String(24),unique=True)
books = db.relationship("Book",backref='author')
mobile = db.Column(db.String(11))
class Book(db.Model):
'''书'''
__tablename__ = 'tbl_books' # 指明数据库的表名
id = db.Column(db.SmallInteger, primary_key=True) # 整形的主键默认自增主键
name = db.Column(db.String(32),unique=True)
author_id = db.Column(db.SmallInteger, db.ForeignKey('tbl_authors.id')) # 外键的类型必须和他所关联的属性一致
# 创建表单模型类
class AuthorBookForm(FlaskForm):
'''作者数据表单模型类'''
author_name = StringField(label='作者',validators=[DataRequired('作者必填')])
book_name = StringField(label='书籍',validators=[DataRequired('书籍必填')])
submit = SubmitField(label='保存')
@app.route('/',methods=['GET','POST'])
def index():
form = AuthorBookForm()
if form.validate_on_submit():
# 验证表单成功,提取表单数据
author_name = form.author_name.data
book_name = form.book_name.data
# 保存数据
author = Author(name=author_name)
db.session.add(author)
db.session.commit()
book = Book(name=book_name,author_id =author.id)
print(author_name,book_name,book)
book = Book(name=book_name,author=author)
db.session.add(book)
db.session.commit()
# 查询数据
author_li = Author.query.all()
return render_template('author_book.html',authors =author_li,form=form)
# return '你好啊'
#
if __name__ == '__main__':
# 清除数据库里的所有数据(第一次使用时用,清除数据库中是脏数据)
# db.drop_all()
#
# # 创建所有的表
# db.create_all()
#
# # 创建对象
# au_xi = Author(name='我吃西红柿')
# au_qian = Author(name='萧潜')
# au_san = Author(name='唐家三少')
# # session记录对象任务
# db.session.add_all([au_xi, au_qian , au_san])
# # 提交任务到数据库中
# db.session.commit()
#
# bk_xi = Book(name='吞噬星空',author_id=au_xi.id)
# bk_xi2 = Book(name='寸芒',author_id=au_xi.id)
# bk_qian = Book(name='缥缈之旅',author_id=au_qian.id)
# bk_san = Book(name='冰火魔厨',author_id=au_qian.id)
# db.session.add_all([bk_xi,bk_xi2,bk_qian,bk_san])
# # 提交任务到数据库中
# db.session.commit()
# app.run(debug=True)
# 通过manager对象启动
manager.run()
对应的 templates/author_book.html 用js的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post">
{{ form.csrf_token }}
{{ form.author_name.label }}
<p>{{ form.author_name }}</p>
{% for msg in form.author_name.errors %}
<p>{{ msg }}</p>
{% endfor %}
{{ form.book_name.label }}
<p>{{ form.book_name }}</p>
{% for msg in form.book_name.errors %}
<p>{{ msg }}</p>
{% endfor %}
{{ form.submit }}
</form>
<hr/>
<ul>
{% for author in authors %}
<li>作者:{{ author.name }}</li>
<ul>
{% for book in author.books %}
<li>书籍:{{ book.name }}</li>
<a href="javascript:;" onclick="deleteBook({{ book.id }})">删除</a>
{% endfor %}
</ul>
{% endfor %}
</ul>
<script type="text/javascript" src="/statics\js\jquery-3.3.1.min.js"></script>
</body>
</html>
对应的 templates/author_book.html 没用js的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post">
{{ form.csrf_token }}
{{ form.author_name.label }}
<p>{{ form.author_name }}</p>
{% for msg in form.author_name.errors %}
<p>{{ msg }}</p>
{% endfor %}
{{ form.book_name.label }}
<p>{{ form.book_name }}</p>
{% for msg in form.book_name.errors %}
<p>{{ msg }}</p>
{% endfor %}
{{ form.submit }}
</form>
<hr/>
<ul>
{% for author in authors %}
<li>作者:{{ author.name }}</li>
<ul>
{% for book in author.books %}
<li>书籍:{{ book.name }}</li>
<a href="javascript:;" onclick="deleteBook({{ book.id }})">删除</a>
{% endfor %}
</ul>
{% endfor %}
</ul>
<script type="text/javascript" src="/statics\js\jquery-3.3.1.min.js"></script>
</body>
</html>
数据库迁移文件:migrate.py
# _*_ encoding: utf-8 _*_ @author: ty hery 2019/12/20
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, EqualTo
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand
app = Flask(__name__)
manager = Manager(app)
app.config['SQLALCHEMY_DATABASE_URL'] = 'mysql://root:666@127.0.0.1/flask_test'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
# 第一个参数是Flask的实例,第二个参数是Sqlalchemy数据库实例,创建flask脚本管理工具
migrate = Migrate(app, db)
# managet是Flask-Script的实例,这条语句在flask_Script中添加一个db命令
manager.add_command('db', MigrateCommand) # python migrate.py db init 和python migrate.py db
# 定义模型Role
class Role(db.Model):
# 定义表名
__table__ = 'roles'
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(64),unique=True)
def __repr__(self):
return 'Role:'.format(self.name)
# 定义模型用户
class User(db.Model):
# 定义表名
__table__ = 'users'
id = db.Colunm(db.Integer,pramary_key=True)
username = db.Column(db.string(64),unique=True,index=True)
def __repr__(self):
return 'User:'.format(self.username)
if __name__ =="__main__":
manager.run()
写入自己的博客中才能记得长久