【发布时间】:2020-06-16 07:38:51
【问题描述】:
当用户上传文件时,我收到了一个zip 文件。 zip 本质上包含一个 json 文件,我想读取和处理它,而不必先创建 zip 文件,然后解压缩它,然后再读取内部文件的内容。
目前我只有较长的过程,如下所示
import json
import zipfile
@csrf_exempt
def get_zip(request):
try:
if request.method == "POST":
try:
client_file = request.FILES['file']
file_path = "/some/path/"
# first dump the zip file to a directory
with open(file_path + '%s' % client_file.name, 'wb+') as dest:
for chunk in client_file.chunks():
dest.write(chunk)
# unzip the zip file to the same directory
with zipfile.ZipFile(file_path + client_file.name, 'r') as zip_ref:
zip_ref.extractall(file_path)
# at this point we get a json file from the zip say `test.json`
# read the json file content
with open(file_path + "test.json", "r") as fo:
json_content = json.load(fo)
doSomething(json_content)
return HttpResponse(0)
except Exception as e:
return HttpResponse(1)
如您所见,这涉及到最终将 zip 文件中的内容放入内存的 3 个步骤。我想要的是获取zip文件的内容并直接加载到内存中。
我确实在堆栈溢出中发现了一些类似的问题,例如https://stackoverflow.com/a/2463819。但我不确定我在什么时候调用帖子中提到的这个操作
我怎样才能做到这一点?
注意:我在后端使用 django。 zip 中总会有一个 json 文件。
【问题讨论】:
标签: python django file zip in-memory