内部服务器错误Flask - Python

时间:2015-07-07 05:41:39

标签: python flask sqlalchemy flask-sqlalchemy

这是我在Python中的代码 - Flask。在这里,我输入剧院(剧院表)的数据,然后获取相应的ID,然后将屏幕添加到屏幕表中相应的theatre_id。

问题是剧院被添加到数据库中,我可以获取id。屏幕的代码似乎不起作用(如果我注释掉session.screen add和commit语句,for循环确实有效) 如果屏幕提交没有发生,即使回滚也不会发生。

session_theatre = Session_theatre()
session_screen = Session_screen()
id = 1
if request.method == "POST":
    if form.validate_on_submit():
        name = str(form.name.data)
        city = str(form.location.data)
        address = str(form.address.data)
        no_of_screen = int(form.total_no_screen.data)
        if (name !="" and name!=" " and city != "" and city != " " and address != ""and address != " " and no_of_screen != None):
            t = Theatre(name,city,address,1)
            try:
                session_theatre.add(t)
                session_theatre.commit()
                query = session_theatre.query(Theatre).filter_by(name=name,city =city).all()
                for i in query :
                    id = i
                for i in range (0,no_of_screen):
                    flash(id)
                    screen = Screen(str(i+1),1,20,1,20,id)
                    session_screen.add(screen)
                    session_screen.commit()
                flash("Successfully added !!")
            except :
                session_screen.rollback()
                session_theatre.rollback()
                flash("Oops something went wrong !!")
            finally:
                session_screen.close()
                session_theatre.close()
        else :
            flash("Please fill the input")
return render_template('admin/add_theatre.html',form = form)

屏幕模型

class Screen(db.Model):
    __tablename__ = "screens"
    id = db.Column(db.Integer,primary_key=True)
    screen_num = db.Column(db.String(1))
    seat_row_start = db.Column(db.Integer)
    seat_row_end = db.Column(db.Integer)
    seat_col_start = db.Column(db.Integer)
    seat_col_end = db.Column(db.Integer)
    theatre_id =  db.Column(db.Integer, db.ForeignKey('theatres.id'))

    def __init__(self, screen_num, 
    seat_row_start,seat_row_end,seat_col_start,seat_col_end,theatre_id):
        self.screen_num = screen_num
        self.seat_row_start = seat_row_start
        self.seat_row_end = seat_row_end
        self.seat_col_start = seat_col_start
        self.seat_col_end = seat_col_end
        self.theatre_id = theatre_id

1 个答案:

答案 0 :(得分:0)

要从session_theatre的查询中获取列表,您必须在最后添加all()

query = session_theatre.query(Theatre).filter_by(name=name,city =city).all()

查询返回Theatre个对象的列表,您可以访问每个id对象的Theatre属性,迭代列表并按名称访问该属性:

for obj in query :
    for i in range (0,no_of_screen):
        flash(obj.id)
        screen = Screen(i+1,1,20,1,20,obj.id)
        session_screen.add(screen)
        session_screen.commit()