Flask会话成员在请求间未保持

4 投票
2 回答
3952 浏览
提问于 2025-04-16 23:49

我正在写一个小应用程序,用来查看一个很大的XML文件,并且使用一些类似AJAX的方式来调用viewgroup。我遇到的问题是session['groups']没有保持住。现在有一个旧的数组,里面只有4个成员,似乎卡在某个地方(可能是cookie?)。当调用view时,这个值是存在的。然后我用最近打开的XML文件中的信息覆盖了这个会话变量,那个文件里有20多个成员。

但是,当调用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

可能你的数据太大了。

如果你的数据超过了4KB,就需要在服务器端使用会话管理。可以看看这个链接:Flask-Session

8

数据实在太大了,无法直接存储到会话中。现在我生成一个键,放到一个全局字典里,然后把这个键存到会话里。

gXmlData[path] = groups    

但是这样有个问题,全局字典会一直存在,键会越来越多,而这个过程其实并不打算长时间运行。

撰写回答