Sou*_*Ray 3 python django zip file in-memory
我有一个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)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这涉及 3 个步骤才能最终将文件中的内容读取zip到内存中。我想要的是获取文件的内容zip并直接加载到内存中。
我确实在堆栈溢出中发现了一些类似的问题,例如/sf/answers/172467361/。但我不确定在什么时候调用帖子中提到的这个操作
我怎样才能实现这个目标?
注意:我在后端使用 django。zip 中总会有一个 json 文件。
据我了解,@jason在这里想说的是首先打开一个 zipFile,就像你在这里所做的那样 with zipfile.ZipFile(file_path + client_file.name, 'r') as zip_ref:。
class zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
Open a ZIP file, where file can be either a path to a file (a string) or a file-like object.
Run Code Online (Sandbox Code Playgroud)
然后使用BytesIO读取类文件对象的字节。但从上面看,你是在r模式下阅读,而不是rb在模式下阅读。因此,将其更改如下。
with open(filename, 'rb') as file_data:
bytes_content = file_data.read()
file_like_object = io.BytesIO(bytes_content)
zipfile_ob = zipfile.ZipFile(file_like_object)
Run Code Online (Sandbox Code Playgroud)
现在zipfile_ob可以从内存中访问。
第一个参数zipfile.ZipFile()可以是文件对象而不是路径名。我认为 DjangoUploadedFile对象支持这种用法,因此您可以直接从中读取内容,而不必复制到文件中。
您还可以直接从 zip 存档中打开文件,而不是将其提取到文件中。
import json
import zipfile
@csrf_exempt
def get_zip(request):
try:
if request.method == "POST":
try:
client_file = request.FILES['file']
# unzip the zip file to the same directory
with zipfile.ZipFile(client_file, 'r') as zip_ref:
first = zip_ref.infolist()[0]
with zip_ref.open(first, "r") as fo:
json_content = json.load(fo)
doSomething(json_content)
return HttpResponse(0)
except Exception as e:
return HttpResponse(1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8537 次 |
| 最近记录: |