标签:deb 表之间 访问 mysql orm .config lang dex conf
模型建立一一对多模型:
from flask import Flask # Flask参数,可以配置静态文件路由,及文件夹 from flask import render_template from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config[‘SQLALCHEMY_DATABASE_URI‘] = ‘mysql://root:mysql@127.0.0.1:3306/test2‘ app.config[‘SQLALCHEMY_TRACK_MODIFICATIONS‘] = True db = SQLAlchemy(app) 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(‘Books‘, backref=‘author‘) def __repr__(self): return ("Author:%s")%self.name class Books(db.Model): __tablename__ = ‘books‘ id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(64),unique=True) author_id = db.Column(db.Integer,db.ForeignKey(‘author.id‘)) def __str__(self): return ("Books:%s")%self.name @app.route("/books") def index(): authors = Author.query.all() return render_template(‘books.html‘,authors=authors) if __name__ == "__main__": app.run(debug=True)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图书管理</title> </head> <body> <h1>图书管理系统</h1> <br> <ul> {% for author in authors %} <li>{{ author.name }}</li> <ul> {% for book in author.au_book %} <li>{{ book.name }}</li> {% endfor%} </ul> {% endfor %} </ul>
</body> </html>
class AddBookForm(FlaskForm): author = StringField(‘作者‘,validators=[InputRequired(‘请输入作者‘)]) book = StringField(‘书籍‘,validators=[InputRequired(‘请输入书名‘)]) submit = SubmitField(‘添加‘) @app.route("/books") def index(): book_author_form = AddBookForm() authors = Author.query.all() return render_template(‘books.html‘,authors=authors,form=book_author_form)
<form action="post"> {{ form.csrf_token() }}<br> {{ form.author.label }}{{ form.author }}<br> {{ form.book.label }}{{ form.book }}<br> {{ form.submit }} </form>
标签:deb 表之间 访问 mysql orm .config lang dex conf
原文地址:https://www.cnblogs.com/alicelai1319/p/10281494.html