模型分离--让代码更方便管理
新建models.py,将模型定义全部放到这个独立的文件中。
新建exts.py,将db = SQLAlchemy()的定义放到这个独立的文件中。
models.py和主py文件,都从exts.py中导入db。
在主py文件中,对db进行始化,db.init_app(app)。
models.py
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(20), nullable=False) nickname = db.Column(db.String(20), nullable=True) class Wenda(db.Model): __tablename__ = ‘wenda‘ 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(‘wenda‘)) 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‘)) wenda_id = db.Column(db.Integer, db.ForeignKey(‘wenda.id‘)) creat_time = db.Column(db.DateTime, default=datetime.now) detail = db.Column(db.Text, nullable=False) wenda = db.relationship(‘Wenda‘, backref=db.backref(‘comments‘,order_by=creat_time.desc)) author = db.relationship(‘User‘, backref=db.backref(‘comments‘))
exts.py
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
主py文件
from functools import wraps from flask import Flask, render_template, url_for, redirect, request, session import config from sqlalchemy import or_,and_ from exts import db from models import User,Wenda,Comment app = Flask(__name__) # 创建Flask对象 app.config.from_object(config) # 关联config.py文件进来 db.init_app(app) # 建立和数据库的关系映射 ...
原文地址:https://www.cnblogs.com/guomeiting/p/8116850.html
时间: 2024-11-08 13:09:35