Python 请求之间的数据模型持久性

Python 请求之间的数据模型持久性,python,session,flask,flask-sqlalchemy,Python,Session,Flask,Flask Sqlalchemy,我正在使用Flask和Flask SQLAlchemy构建一个应用程序 在应用程序中,我使用用SQLAlchemy声明性语言编写的数据库模型,假设我有一个名为Server的表。 通过设计选择,应用程序要求用户通过WTForms在不同页面(视图)之间设置服务器表字段的值,我需要将实例保存到最后一个视图中的数据库中 我的问题是:我有两个“循环”视图,希望将第一个视图中创建的对象实例直接存储在数据库会话中,以便能够在第二个视图中查询会话,并仅在最后一个视图(循环结束)中提交结果,如伪代码所示(非常简

我正在使用Flask和Flask SQLAlchemy构建一个应用程序

在应用程序中,我使用用SQLAlchemy声明性语言编写的数据库模型,假设我有一个名为Server的表。 通过设计选择,应用程序要求用户通过WTForms在不同页面(视图)之间设置服务器表字段的值,我需要将实例保存到最后一个视图中的数据库中


我的问题是:我有两个“循环”视图,希望将第一个视图中创建的对象实例直接存储在数据库会话中,以便能够在第二个视图中查询会话,并仅在最后一个视图(循环结束)中提交结果,如伪代码所示(非常简单,在这种形式下没有意义,只是为了解释概念):

def first_view():
form=FormOne()#提示第一个表单
if form.validate_on_submit():
#表单验证,我在SQLalchemy中创建实例
服务器=服务器()#数据库模型
server.hostname=form.hostname.data
循环计数=form.repeation.data
会话['loop']=循环计数
db.session.add(服务器)#将对象添加到会话
#但是我没有提交会话,事实上下一个视图需要知道这个新对象,第三个视图需要根据用户输入提交
返回重定向(url_for('second_view'))
返回渲染模板(“first\u view.html”,form=form)
def第二视图():
form=FormTwo()#提示第二个表单
if form.validate_on_submit():
hostname_to_search=form.hostname.data#我得到一些其他输入
#我使用输入来查询会话(此处可能会出现不同的服务器Instance,具体取决于第一个视图的用户输入)
rslt=db.session.query(Server.filter(Server.hostname==hostname\u to\u search).all()
#会话为空,不包含在上一个视图中创建的实例。。。
def first_view():
form = FormOne() #prompt the first form
if form.validate_on_submit():
    #form validate, i create the instance in SQLalchemy
    server = Server() #Database Model
    server.hostname = form.hostname.data
    loop_count = form.repetition.data
    session['loop'] = loop_count 
    db.session.add(server) #adding the object to the session
    #but i'm not committing the session in fact the next view needs to know about this new object and a third view needs to commit based on the user input
    return redirect(url_for('second_view'))
return render_template("first_view.html", form=form)

def second_view():
form = FormTwo() #prompt the second form
if form.validate_on_submit():
    hostname_to_search = form.hostname.data #i get some other input
    #i use the input to query the session (here different server instace can appear, depends on the user input of the first view)
    rslt= db.session.query(Server).filter(Server.hostname==hostname_to_search ).all()
    #the session is empty and doesn't contain the instance created in the previous view... <-- :(

    if session['loop'] <= 0 :
       #end the loop
       return redirect(url_for('commit_view'))
    else:
      loop_count = session.pop('loop',1)
      session['loop'] = loop_count-1
      #go back to the first page to add another server instance
      return redirect(url_for('first_view')) 
return render_template("first_view.html", form=form)


def commit_view():
    #loop finished, now i can commit my final instances
    db.session.commit() <--here i save the data, db.session is empty 
return 'DONE!'