0

I am looking to have a flask API which takes in a zipfile as the input request and the function reads the zip file, extracts its contents and stores it one the system, in the directory where the flask api is running.

Here is the sample code I am using on a Linux environment:

import os,sys

from flask import Flask,request,Response

UPLOAD_FOLDER = os.path.dirname(os.path.realpath(__file__))
app = Flask(__name__)

@app.route("/invocations",methods=["POST"])
def data_extraction():
#check if input is a zipfile
if request.content_type == 'application/zip'
   try:
      file = request.files
      file.save(os.path.join(UPLOAD_FOLDER,file_name))
      zip_ref = zipfile.ZipFile(os.path.join(UPLOAD_FOLDER, file_name), 'r')
      zip_ref.extractall(UPLOAD_FOLDER)
      zip_ref.close()
      return "file unzipped"
  except Exception as e:
      return Response(response='Invalid content type', status=500)

On running this I get the response "Invalid content type with the following error: 'ImmutableMultiDict' object has no attribute 'save'

Is there a correct way to take in zip files as the input? Not sure if BytesIO or some other inpur format is required. I need to take the zipfile from input request and pass it through this function which extracts the zipfile and stores it on the system.

B2A3R9C9A
  • 29
  • 6

1 Answers1

1

Per the docs (https://flask.palletsprojects.com/en/2.1.x/api/#flask.Request), yes, files is a dictionary type. The values are FileStorage objects, so you'll want to work on those.

Also, you have a typo in your app.route decorator - metjods. I'm surprised the code isn't erroring.

ndc85430
  • 1,395
  • 3
  • 11
  • 17
  • the typo was while pasting the code on SO. Didnt get a syntax error while running code on the system. Regarding the question, is there a way to hold the file as a value using FileStorage objects and then proceed to extract it? – B2A3R9C9A Jun 16 '22 at 04:56
  • You need to access the value from the dict by its key as always. – ndc85430 Jun 16 '22 at 05:14
  • I'm also not sure how you can get a typo when copying and pasting code. – ndc85430 Jun 16 '22 at 05:15