【问题标题】:Flask session member not persisting across requestsFlask 会话成员不会跨请求持续存在
【发布时间】:2011-10-29 08:13:34
【问题描述】:

我正在编写一个快速应用程序来查看一个巨大的 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 个小组都留在附近。有什么提示吗?

【问题讨论】:

    标签: python flask


    【解决方案1】:

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

    gXmlData[path] = groups    
    

    存在的问题是全局 dict 会随着越来越多的键永远存在,但这个过程并不意味着长期存在。

    【讨论】:

    【解决方案2】:

    也许你的数据太大了。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-03
      • 2019-04-19
      • 1970-01-01
      • 2016-04-12
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多