如何decode/read Flask文件系统会话文件?

How to decode/read Flask filesystem session files?

我有一个 Python3 Flask 应用程序使用 Flask-Session(它添加了服务器端会话支持)并配置为使用 filesystem 类型。

该类型底层使用 Werkzeug class werkzeug.contrib.cache.FileSystemCache (Werkzeug cache documentation).

如果打开,原始缓存文件如下所示:

J¬».].Äï;}î(å
_permanentîàå
respondentîåuuidîåUUIDîìî)Åî}î(åintîät˙ò∑flŒºçLÃ/∆6jhåis_safeîhåSafeUUIDîìîNÖîRîubåSECTIONS_VISITEDî]îåcurrent_sectionîKåSURVEY_CONTENTî}î(å0î}î(ås_idîås0îånameîåWelcomeîådescriptionîåîå   questionsî]î}î(ås_idîhåq_idîhåq_constructîhåq_textîhå
q_descriptionîhåq_typeîhårequiredîhåoptions_rowîhåoptions_row_alpha_sortîhåreplace_rowîhåoptions_colîhåoptions_col_codesîhåoptions_col_alpha_sortîhåcond_continue_rules_rowîhåq_meta_notesîhuauå1î}î(hås1îhå    Screeningîhå[This section determines if you fit into the target group.îh]î(}î(hh/håq1îh hh!å9Have you worked on a product in this field before?

session中存储的items可以在上面看到一点: - current_section 应该是一个整数,例如 0 - SECTIONS_VISITED 应该是整数数组,例如 [0,1,2] - SURVEY_CONTENT 格式应该是具有如下结构的对象

{
  'item1': {
    'label': string,
    'questions': [{}]
  }, 
  'item2': {
    'label': string,
    'questions': [{}]
  }
}

你在上面的摘录中可以看到,例如文本 This section determines if you fit into the target group 是一个标签的值。 questions 之后的内容是可以在每个 questions 对象中找到的键,例如 q_text 以及它们的值,例如 Have you worked on a product in this field before? 是 [=26 的值=].

我需要以一种无需像 å 这样的额外字符就能读取的方式从存储的缓存文件中检索数据。

我试过这样使用 Werkzeug,其中 9c3c48a94198f61aa02a744b16666317 项是我要读取的缓存文件的名称。但是在缓存目录中没有找到。

from werkzeug.contrib.cache import FileSystemCache
cache_dir="flask_session"
mode=0600
threshold=20000
cache = FileSystemCache(cache_dir, threshold=threshold, mode=mode)
item = "9c3c48a94198f61aa02a744b16666317"
print(cache.has(item))
data = cache.get(item)
print(data)

缓存文件的读取方式有哪些?

我在 Flask-Session 中打开了一个 GitHub issue,但多年来并没有真正积极地维护它。

对于上下文,我有一个实例,其中我的网络应用程序写入数据库暂时不起作用 - 但我需要的数据也保存在会话中。所以现在检索该数据的唯一方法是从这些文件中获取它。

编辑:

感谢 Tim 的回答,我使用以下方法解决了它:

import pickle
obj = []
with open(file_name,"rb") as fileOpener:
    while True:
        try:
            obj.append(pickle.load(fileOpener))
        except EOFError:
            break
print(obj)

我需要加载文件中的所有 pickled 对象,所以我将 Tim 的解决方案与此处的解决方案结合起来用于加载多个对象:

没有这个,我只是看到第一个腌制的东西。

此外,如果有人遇到同样的问题,我需要使用与我的 Flask 应用程序 (related post) 相同的 python 版本。如果我不这样做,那么我会得到以下错误:

ValueError: unsupported pickle protocol: 4

您可以使用 pickle 解码数据。 Pickle 是 Python 标准库的一部分。

import pickle

with open("PATH/TO/SESSION/FILE") as f:
    data = pickle.load(f)