models.py
新建models.py,将模型定义全部放到这个独立的文件中。
from datetime import datetimefrom werkzeug.security import generate_password_hash,check_password_hash
from exts import db
class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=TabError, autoincrement=True) username = db.Column(db.String(20), nullable=False) _password = db.Column(db.String(200), nullable=False) #neibushiyong nickname = db.Column(db.String(20)) @property def password(self): return self._password @password.setter def password(self, row_password): self._password = generate_password_hash(row_password) def check_password(self, row_password): result = check_password_hash(self._password, row_password) return resultclass Question(db.Model): __tablename__ = 'question' id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(100), nullable=False) detail = db.Column(db.Text, nullable=False) creat_time = db.Column(db.DateTime, default=datetime.now) author_id = db.Column(db.Integer, db.ForeignKey('user.id')) author = db.relationship('User', backref=db.backref('question'))class Comment(db.Model): __tablename__='comment' id = db.Column(db.Integer, primary_key=True, autoincrement=True) author_id = db.Column(db.Integer, db.ForeignKey('user.id')) question_id = db.Column(db.Integer , db.ForeignKey('question.id')) creat_time = db.Column(db.DateTime,default=datetime.now) detail = db.Column(db.Text , nullable=False) question = db.relationship('Question',backref = db.backref('comments',order_by=creat_time.desc)) author = db.relationship('User',backref = db.backref('comments'))
新建exts.py,将db = SQLAlchemy()的定义放到这个独立的文件中。
from flask_sqlalchemy import SQLAlchemydb = SQLAlchemy()
models.py和主py文件,都从exts.py中导入db。
在主py文件中,对db进行始化,db.init_app(app)。
from models import Question,User,Commentfrom exts import dbapp=Flask(__name__)app.config.from_object(config)db.init_app(app)