簡體   English   中英

Flask 會話成員不會跨請求持續存在

[英]Flask session member not persisting across requests

我正在編寫一個快速應用程序來查看一個巨大的 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 個小組都留下來。 任何提示?

數據太大而無法序列化到會話中。 現在我在全局字典中生成一個密鑰並將該密鑰存儲在會話中。

gXmlData[path] = groups    

存在的問題是全局 dict 會隨着越來越多的鍵而永遠存在,但這個過程並不意味着長久存在。

也許你的數據太大了。

如果您的數據大於 4KB,則需要服務器端會話。 看看Flask-Session

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM