在Flask中的模板之间传递会话变量

时间:2015-07-06 12:50:18

标签: python flask

我正在尝试在一个模板中分配会话变量并将其传递给另一个模板,但我不断收到KeyError: 'var'错误。我不确定我在这里做错了什么。我的views.py看起来如下:

from flask import Flask, request, jsonify, session
from app import app
@app.route('/activity', methods=['GET', 'POST'])
def activity():
    user = session['var']
    location = {'mspace': 'Central Library'} 
    return render_template('activity.html',
                            location = location,
                            user = user)

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index(): 
    global checkCheck
    print "starting"
    if request.method == 'POST':
        # print(request.data)
        checkCheck = True
        location = {'mspace': 'Central Library'} 
        user = {'nickname': request.args.get('name')}
        session['var'] = user
        # print user['nickname']
        print session['var']
        return render_template('index.html',
                    location = location,
                    user = user) 

    return render_template('index.html', 
                            location = "test", 
                            user = 'user')

这是我的activity.html:

<html>
    <head>
        <title>{{ location['mspace'] }} - Makerspace </title>
    </head>
    <body>
      <h1>Hello, {{ user['nickname'] }} - what activity are you doing today:</h1>

      <form action="" method="">
        <h3> Choose your Activity</h3>
        <select name="activity"> 
            <option value='3dprinting'>3D Printing</option>
            <option value='Minecraft'>Minecraft</option>
            <option value='Arduino'>Arduino</option>
            <option value='Wearables'>Wearables</option>
        </select>

    </body>
</html>

这是我的index.html:

<html>
    <head>
        <title>{{ location['mspace'] }} - Makerspace </title>
    </head>
    <body>
      <h1>Hello, {{ user['nickname'] }}!</h1>
    </body>

    <script>

    function httpGet(theUrl)
    {
               var xmlHttp = new XMLHttpRequest();
               xmlHttp.open( "GET", theUrl, false );
               xmlHttp.send(null);
               return xmlHttp.responseText;
    }

    setInterval(checkFunc(), 1000);

    function checkFunc(){
        var json = httpGet("/getSignIn");
            console.log("yes!");
            obj = JSON.parse(json);
            console.log(obj.newCheckin);
            if(obj.newCheckin){
                window.location.replace("http://127.0.0.1:5000/activity");
            }
            else{
                setInterval(checkFunc(), 1000);
            }
    }

  </script>
</html>

0 个答案:

没有答案