我正在创建一个应用程序来替换浏览器中的当前选项卡管理器。我在组 - 表主题和选项卡 - 表选项卡之间创建了一个简单的一对多关系。如果我删除它,我希望能够自动删除主题的孩子。这是我目前拥有的:
from flask import request, redirect, url_for, render_template, Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import exc
from flask_whooshee import Whooshee
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
whooshee = Whooshee(app)
@whooshee.register_model('topic_name')
class Topic(db.Model):
__tablename__ = 'topic'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
topic_name = db.Column(db.String, unique=True, nullable=False)
topic_created = db.Column(db.DateTime, default=datetime.utcnow)
topic_changed = db.Column(db.DateTime, default=datetime.utcnow)
topic_tabs = db.relationship('Tab', backref='topic', cascade='all, delete-orphan', lazy='dynamic')
@whooshee.register_model('tab_name', 'tab_link', 'tab_description')
class Tab(db.Model):
__tablename__ = 'tab'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
tab_name = db.Column(db.String, nullable=False)
tab_link = db.Column(db.String, unique=True, nullable=False)
tab_favicon = db.Column(db.String)
tab_description = db.Column(db.String)
tab_created = db.Column(db.DateTime, default=datetime.utcnow)
tab_changed = db.Column(db.DateTime, default=datetime.utcnow)
topic_id = db.Column(db.Integer, db.ForeignKey('topic.id'))
@app.route('/', methods=['GET'])
def index():
return "Test"
if __name__ == '__main__':
db.create_all()
try:
db.session.commit()
except exc.IntegrityError as e:
print(str(e))
db.session.rollback()
top = Topic(topic_name='Test')
db.session.add(top)
try:
db.session.commit()
except exc.IntegrityError as e:
print(str(e))
db.session.rollback()
问题是当我尝试在数据库中添加某些内容时出现完整性错误,但我不确定会出现什么问题。如果我停止服务器,我还想将以前的记录保存在数据库中,我该如何实现?
相关分类