Flask会话成员不会跨请求持久化

时间:2011-08-17 22:30:17

标签: python flask

我正在编写一个快速应用程序来查看一个巨大的XML文件,其中包含对viewgroup的一些AJAX样式调用。我的问题是session['groups']没有坚持。我有一些旧的阵列只有4个成员卡在某处(cookie?..)。调用view时会显示该值。然后,我用最近打开的包含20多个成员的xml文件中的信息覆盖该会话成员。

但是,当调用viewgroup时,会话变量已恢复为旧值,阵列中只有4个成员!

代码后跟输出。请注意3 sessionStatus()次调用

def sessionStatus():
    print "# of groups in session = " + str(len(session['groups']))

@app.route('/')
def index():
    cams = [file for file in os.listdir('xml/') if file.lower().endswith('xml')]
    return render_template('index.html', cam_files=cams)

@app.route('/view/<xmlfile>')
def view(xmlfile):
    path = 'xml/' + secure_filename(xmlfile)
    print 'opening ' + path
    xmlf = open(path, 'r')
    tree = etree.parse(xmlf)
    root = tree.getroot()
    p = re.compile(r'Group')
    groups = []
    for g in root:
        if (p.search(g.tag) is not None) and (g.attrib['Comment'] != 'Root'):
            groups.append(Group(g.attrib['Comment']))
    sessionStatus()
    session['groups'] = groups
    sessionStatus()
    return render_template('view.html', xml=xmlfile, groups=groups)

@app.route('/viewgroup/<name>')
def viewGroup(name):
    groups = session['groups']
    sessionStatus()        
    if groups is None or len(groups) == 0:
        raise Exception('invalid group name')
    groups_filtered = [g for g in groups if g.name == name]
    if len(groups_filtered) != 1:
        raise Exception('invalid group name', groups_filtered)
    group = groups_filtered[0]
    prop_names = [p.name for p in group.properties]
    return prop_names

输出

opening xml/d.xml
# of groups in session = 5
# of groups in session = 57
127.0.0.1 - - [17/Aug/2011 17:27:29] "GET /view/d.xml HTTP/1.1" 200 -
127.0.0.1 - - [17/Aug/2011 17:27:29] "GET /static/ivtl.css HTTP/1.1" 304 -
127.0.0.1 - - [17/Aug/2011 17:27:29] "GET /static/jquery.js HTTP/1.1" 304 -
127.0.0.1 - - [17/Aug/2011 17:27:29] "GET /static/raphael-min.js HTTP/1.1" 304 -
127.0.0.1 - - [17/Aug/2011 17:27:29] "GET /static/ivtl.css HTTP/1.1" 304 -
127.0.0.1 - - [17/Aug/2011 17:27:29] "GET /favicon.ico HTTP/1.1" 404 -
# of groups in session = 5
127.0.0.1 - - [17/Aug/2011 17:27:31] "GET /viewgroup/DeviceInformation HTTP/1.1" 200 -

我需要所有57个团体留下来。任何提示?

2 个答案:

答案 0 :(得分:8)

数据太大而无法序列化到会话中。现在,我将一个密钥生成一个全局字典并将该密钥存储在会话中。

gXmlData[path] = groups    

有一个问题是,全局字典会随着越来越多的密钥而永远存在,但这个过程并不意味着长寿。

答案 1 :(得分:0)

也许你的数据太大了。

如果您的数据大于 4KB,则需要服务器端会话。看看Flask-Session