www.lynda.com作为全球一流的在线培训网站,一直以高质量的视频课程著称。其课程内容也是紧跟行业潮流,本人最近学了里面的一门课程Learning Python and Django, 分享一下。
课程链接:https://www.lynda.com/Django-tutorials/Up-Running-Python-Django/386287-2.html
获取lynda.com永久会员的链接:https://item.taobao.com/item.htm?id=557746408785
实现功能:
数据库:
作者: ---id ---name-- backref 'BOOK'
图书: ---id----name--- author_id外键
代码:
1. 配置文件
# coding: utf-8
class Config(object):
SECRET_KEY = 'SDIGBIUIU3289SD2I3U589$445SG'
SQLALCHEMY_DATABASE_URI = 'mysql://root:[email protected]:3306/db_books'
SQLALCHEMY_TRACK_MODIFICATIONS = True
2. 程序文件
# coding: utf-8
"""
图书管理系统:
1. 实现图书和作者的添加功能
2. 实现动态查询显示图书信息
3. 实现删除功能
4. 实现通过查询作者显示对应的图书信息
5. 实现通过输入图书查询作者信息
"""
from flask import Flask, render_template, redirect, flash, url_for,request
from config import Config
# 1. 导入Alchemy对象
from flask_sqlalchemy import SQLAlchemy
# 导入表单类
from flask_wtf import FlaskForm
# 导入表单字段
from wtforms import StringField, SubmitField
# 导入验证函数
from wtforms.validators import DataRequired
# 定义表单类,继承自FlaskForm, 在该类中定义字段
class Form(FlaskForm):
"""定义模型表格"""
book = StringField(validators=[DataRequired()])
author = StringField(validators=[DataRequired()])
submit = SubmitField(label=u'添加')
app = Flask(__name__)
app.config.from_object(Config)
# 2. 实例化SQLALchemy
db = SQLAlchemy(app)
# 3. 定义数据表
class Author(db.Model):
"""定义作者"""
__tablename__ = 'author'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(32), unique=True)
au_book = db.relationship('Book', backref='author')
class Book(db.Model):
"""定义书籍数据表"""
__tablename__ = 'book'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(32), unique=True)
author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
# 实例化Flaskform
form = Form()
# 查询数据库,显示数据
try:
books = Book.query.all()
authors = Author.query.all()
except:
flash('错误,信息不存在'.encode('utf-8'))
context = {
'books': books,
'authors': authors,
'form': form,
}
return render_template('index.html', **context)
else:
form = Form()
if form.validate_on_submit():
book_name = form.book.data
author_name = form.author.data
# 检查添加的信息是否已经存在
book = Book.query.filter_by(name=book_name).all()
author = Author.query.filter_by(name=author_name).first()
if book or author:
flash(u'该信息已经存在')
return redirect(url_for('index'))
# 先添加作者信息,以便获取数据库中的author_id作为book的外键盘保存到数据库
author = Author(name=author_name)
try:
author = Author.query.filter_by(name=author_name)[0]
except:
# 添加author信息
db.session.add(author)
db.session.commit()
author = Author.query.filter_by(name=author_name)[0]
# 添加book信息
book = Book(name=book_name, author_id=author.id)
db.session.add(book)
db.session.commit()
flash(u'添加记录成功!')
return redirect(url_for('index'))
else:
flash('数据输入错误'.encode('utf-8'))
return redirect(url_for('index'))
@app.route('/delete_book/', methods=['GET', 'POST'])
def delete_book(id):
"""删除单条记录的视图函数"""
# 查询对应id的数据库记录
book = Book.query.get(id)
db.session.delete(book)
db.session.commit()
return redirect(url_for('index'))
@app.route('/delete_author/', methods=['GET', 'POST'])
def delete_author(id):
"""删除单条记录的视图函数"""
# 查询对应id的数据库记录
author = Author.query.get(id)
books = author.au_book
for book in books:
db.session.delete(book)
db.session.delete(author)
db.session.commit()
return redirect(url_for('index'))
@app.route('/q', methods=['POST'])
def query_data():
"""查询对应的信息"""
q_data = request.form.get('data')
if not all([q_data]):
flash(u'输入信息为空')
return redirect(url_for('index'))
# 尝试查询是否是数据
try:
book = Book.query.filter_by(name=q_data).all()
author = Author.query.filter_by(name=q_data).first()
if book:
author_id = book[0].author_id
author = Author.query.get(author_id)
flash(u'作者: ' + author.name)
elif author:
# 关联查询,查到的是一个对象列表
books = author.au_book
if not books:
flash(u'查询的信息不存在')
else:
for book in books:
flash(u'图书: ' + book.name)
else:
flash(u'查询的信息不存在')
except Exception as e:
flash(u'错误', e)
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
3. html模板文件
图书管理系统
-------------------作者和图书列表-------------------
{% for author in authors %}
- {{author.name}}
{% for book in author.au_book %}
- {{book.name}}删除
{% endfor %}
删除
{% endfor %}
-----------------------------------------------
{% if get_flashed_messages() %}
-----------------------------------------------
{% for message in get_flashed_messages() %}
{{message}}
{% endfor %}
{% endif %}
4. 界面效果: