模型分离(选做)
模型分离--让代码更方便管理
1.新建models.py,将模型定义全部放到这个独立的文件中。
2.新建exts.py,将db = SQLAlchemy()的定义放到这个独立的文件中。
3.models.py和主py文件,都从exts.py中导入db。
4.在主py文件中,对db进行始化,db.init_app(app)。
1.代码如下:
models.py
from werkzeug.security import generate_password_hash,check_password_hash from datetime import datetime from exts import db class User(db.Model): __tablename__ = 'user' # 建立一个表user id = db.Column(db.Integer,primary_key=True,autoincrement=True) username = db.Column(db.String(20),nullable=False) _password = db.Column(db.String(200),nullable=False) image = db.Column(db.String(100)) say = db.Column(db.String(50)) @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 result #db.create_all() # 建立一表question class 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')) classify=db.Column(db.Enum('散文拾贝', '心灵鸡汤','笑谈风声', '随心所欲'),nullable=False) click = db.Column(db.INT, default=0) # db.create_all() # class Log(db.Model): # __tablename__ = 'log' # # 建立一个表log # id = db.Column(db.Integer,primary_key=True,autoincrement=True) # username = db.Column(db.String(20),nullable=False) # password = db.Column(db.String(20),nullable=False) #db.create_all() class Comment(db.Model): __tablename__ = 'comment' # 建立一个表log 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('comment',order_by=creat_time.desc)) author=db.relationship('User',backref=db.backref('comment')) #db.create_all()
2.exts.py
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
3
from exts import db
4.主py
from flask import Flask from flask import render_template,request,redirect,url_for,session import config from sqlalchemy import or_ ,and_ from functools import wraps from models import Question,User,Comment from exts import db app = Flask(__name__) app.config.from_object(config) db.init_app(app)