我想读取通过表单发布请求发送到Flask服务器的特定类型zip文件中的所有文件,而不必将该zip文件存储在磁盘上。
答案 0 :(得分:3)
首先,获取获取zip文件的代码
from flask import Flask, request
app = Flask(__name__)
@app.route("/",methods=["GET"])
def page_name_get():
return """<form action="." method="post" enctype=multipart/form-data>
<input type="file" accept="application/zip" name="data_zip_file" accept="application/zip" required>
<button type="submit">Send zip file!</button>
</form>"""
app.run()
这是帖子请求功能的外观
import zipfile
@app.route("/",methods=["POST"])
def page_name_post():
file = request.files['data_zip_file']
file_like_object = file.stream._file
zipfile_ob = zipfile.ZipFile(file_like_object)
file_names = zipfile_ob.namelist()
# Filter names to only include the filetype that you want:
file_names = [file_name for file_name in file_names if file_name.endswith(".txt")]
files = [(zipfile_ob.open(name).read(),name) for name in file_names]
return str(files)
现在我将逐行浏览
file = request.files['data_zip_file']
首先,您需要从请求中获取文件对象,这是werkzeug.datastructures.FileStorage
类的实例。
file_like_object = file.stream._file
在这里,您首先采用werkzeug.datastructures.FileStorage
的stream属性,这是文件的输入流。这将返回tempfile.SpooledTemporaryFile
的实例,该实例用于临时文件。在该实例中,采用._file属性。这将返回tempfile._TemporaryFileWrapper
的实例,就像zipfile.ZipFile类可以理解的io.BytesIO
一样。
zipfile_ob = zipfile.ZipFile(file_like_object)
在这里创建zipfile.Zipfile
对象
现在,您应该可以执行几乎所有想要使用zip进行的操作。要从zip文件中选择文件,请使用zipfile_ob.open()
方法,然后将路径传递到要打开的文件中。
要获取这些路径,我们使用file_names = zipfile_ob.namelist()
,它将返回一个列表,其中包含zip中所有文件和目录的所有路径的字符串。
然后您可以使用file_names = [file_name for file_name in file_names if file_name.endswith(".txt")]
您想要的所有那些路径现在都位于file_names
中。然后,您可以使用打开功能提取那些文件的数据。
files = [(zipfile_ob.open(name).read(),name) for name in file_names]
在给出的示例中,我将文件的路径保留在最终列表中,但是如果您不希望使用,可以使用:
files = [zipfile_ob.open(name).read() for name in file_names]
或使用其他方式浏览文件。如果您想要有关文件的更多信息,也可以使用infolist()
方法代替namelist()
,这将返回ZipInfo Objects的列表而不是仅字符串的列表。这些对象包含有关所有文件的更多数据。