模型分離

模型分離--讓代碼更方便管理sql

新建models.py,將模型定義所有放到這個獨立的文件中。flask

from datetime import datetime
from 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=True,autoincrement=True)
    username = db.Column(db.String(20),nullable=False)
    _password = db.Column(db.String(200),nullable=False)

    @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

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)
    creatTime=db.Column(db.DateTime,default=datetime.now)
    authorID=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'))
    detail=db.Column(db.Text,nullable=False)
    creatTime=db.Column(db.DateTime,default=datetime.now)
    question=db.relationship('Question',backref=db.backref('comments',order_by=creatTime.desc))
    author=db.relationship('User',backref=db.backref('comments'))

 

新建exts.py,將db = SQLAlchemy()的定義放到這個獨立的文件中。session

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

 

models.py和主py文件,都從exts.py中導入db。app

在主py文件中,對db進行始化,db.init_app(app)。url

from flask import Flask, render_template,request,redirect,url_for,session
import config
from functools import wraps
from exts import db
from sqlalchemy import or_
from models import Question,User,Comment

app = Flask(__name__)
app.config.from_object(config)

db.init_app(app)
相關文章
相關標籤/搜索