Home > OS >  Extract zipfile and store it using flask api
Extract zipfile and store it using flask api

Time:06-16

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.

CodePudding user response:

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.

CodePudding user response:

This is an example to write API receives a file from a client: read multipart form data with flask. After getting the file from the client, you can check this content type

  • Related