zoukankan      html  css  js  c++  java
  • 模型分离(选做)

    模型分离--让代码更方便管理

    新建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'
        id = db.Column(db.Integer, primary_key=True, autoincrement=True)
        username = db.Column(db.String(100), nullable=False)
        _password = db.Column(db.String(500), 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)
        create_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'))
        create_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=create_time.desc))
        author = db.relationship('User',backref=db.backref('comments'))

    新建exts.py,将db = SQLAlchemy()的定义放到这个独立的文件中。

    from flask_sqlalchemy import SQLAlchemy
    
    db = SQLAlchemy()

    models.py和主py文件,都从exts.py中导入db。

    在主py文件中,对db进行始化,db.init_app(app)。

    from models import Question,User,Comment
    from exts import db
    
    app=Flask(__name__)
    app.config.from_object(config)
    db.init_app(app)
  • 相关阅读:
    VS2013编写的C#程序,在xp下会报错说“不是合法的win32程序”。
    能根据串口驱动来 确定com号
    javaweb工程,Servlet里面获取当前WEB跟路径的文件绝对路径地址
    import了sun开头的类,虽然它在代码里压根就没派上用处!但是必须得引用!
    页面关闭时触发的时间
    jquery设置元素的readonly和disabled
    ibatis CDATA
    form的submit与onsubmit的用法与区别
    C#操作AD及Exchange Server总结(一)
    AD如何用C#进行增删改、查询用户与OU
  • 原文地址:https://www.cnblogs.com/00js/p/8117111.html
Copyright © 2011-2022 走看看