向多个路由中的会话添加变量

2024-03-28 13:39:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个应用程序,其中变量在多个路由中分配。每个路由都可以在会话独立时将变量添加到会话中,但是当我尝试在两个路由中分配变量时,会话只会更新第二个路由中的变量。你知道吗

我最初使用的是全局变量而不是会话,程序运行正常。当会话只在一个路由中更新时,它也能正常工作。我想问题可能是因为回来了 '', 204 但当我将调用'/form'的JavaScript切换到ajax并返回jsonify时,问题仍然存在。你知道吗

当两个路由中的会话都被更新时,我会得到一个KeyError。你知道吗

@app.route('/form', methods=['POST'])
def handle_form():
    session['collegeName'] = request.form.get('selector')
    print("/form " + "College Name: " + session['collegeName'])

    for row in collegeData:
        if row[0] == session['collegeName']:
            session['collegeInfo'] = row
    print("/form " + "College Info:", session['collegeInfo'])
    session.modified = True

    return '', 204

@app.route('/', methods=['POST', 'GET'])
def upload():
    tempdir = mkdtemp()
    fileList = {}
    if request.method == 'POST':
        for key, f in request.files.items():
            if key.startswith('file'):
                filepath = os.path.join(tempdir, f.filename)
                f.save(filepath)
                print(filepath)
                print(readFile(filepath))
                fileList[escape(f.filename)] = readFile(filepath)
        session['fileList'] = fileList
    else:
        fileList = {}
    rmtree(tempdir)
    return render_template('index.html')

@app.route('/completed')
def completed():

    print(session['fileList'])

    fileList = {}
    for fileName in session['fileList']:
        fileList[fileName] = highlight(session['fileList'][fileName])
    return render_template('results.html', fileList=fileList, title=session['collegeName'])

session['collegeName']session['collegeInfo']不更新,但session['fileList']更新。你知道吗

“/form”中的print语句也会打印正确的输出“/complete”中的highlight函数未运行,因为highlight()使用session['collegeInfo']。你知道吗


Tags: formapp路由forrequestsessiondefpost