模型分离--让代码更方便管理
新建models.py,将模型定义全部放到这个独立的文件中。
新建exts.py,将db = SQLAlchemy()的定义放到这个独立的文件中。
models.py和主py文件,都从exts.py中导入db。
在主py文件中,对db进行始化,db.init_app(app)。
1
2
3
4
5
|
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
from datetime import datetime from werkzeug.security import generate_password_hash,check_password_hash from exit 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 ) #内部使用 nickname = 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() class Fankui(db.Model): __tablename__ = 'fankui' id = db.Column(db.Integer,primary_key = True ,autoincrement = True ) biaoti = db.Column(db.String( 100 ),nullable = False ) questionDetail = 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( 'fankui' )) 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' )) fankui_id = db.Column(db.Integer,db.ForeignKey( 'fankui.id' )) creat_time = db.Column(db.DateTime, default = datetime.now) detail = db.Column(db.Text,nullable = False ) fankui = db.relationship( 'Fankui' ,backref = db.backref( 'comment' , order_by = creat_time.desc)) author = db.relationship( 'User' ,backref = db.backref( 'comment' )) |
1
2
3
4
5
6
7
8
9
10
11
|
from flask import Flask, render_template,request,redirect,url_for,session # from flask_sqlalchemy import SQLAlchemy import config from functools import wraps from sqlalchemy import or_,and_ from modle import User,Fankui,Comment from exit import db # from datetime import datetime app = Flask(__name__) app.config.from_object(config) db.init_app(app) |