Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python restplus API to upload and dowload files

With python flask_restplus what is correct way to have a post and get methods to get and push a file e.g. xlsx to the server ?

Does the marshaling need to be used for this ?

reference: https://philsturgeon.uk/api/2016/01/04/http-rest-api-file-uploads/

This answer give general info but not in the python>flask>restplus context: REST API File Upload

like image 808
user3313834 Avatar asked Nov 11 '16 12:11

user3313834


People also ask

How do I upload files using flask API?

Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to 'multipart/form-data', posting the file to a URL. The URL handler fetches file from request. files[] object and saves it to the desired location.

How do I accept files on flask API?

In your API backend, you will receive the file by using file = request. files['file'] . The name "file" comes from the name of the input tag in the HTML Form you are using to send the file to your backend. In this example, the backend is saving the uploaded files to UPLOAD_FOLDER .


1 Answers

First you need to configure a parser

# parsers.py
import werkzeug
from flask_restplus import reqparse

file_upload = reqparse.RequestParser()
file_upload.add_argument('xls_file',  
                         type=werkzeug.datastructures.FileStorage, 
                         location='files', 
                         required=True, 
                         help='XLS file')

Then add a new resource to your api namespace

# api.py
import …
import parsers

@api.route('/upload/')
class my_file_upload(Resource):
    @api.expect(parsers.file_upload)
    def post(self):
        args = parsers.file_upload.parse_args()
        if args['xls_file'].mimetype == 'application/xls':
            destination = os.path.join(current_app.config.get('DATA_FOLDER'), 'medias/')
            if not os.path.exists(destination):
                os.makedirs(destination)
            xls_file = '%s%s' % (destination, 'custom_file_name.xls')
            args['xls_file'].save(xls_file)
        else:
            abort(404)
        return {'status': 'Done'}

I hope this helps.

like image 85
k3z Avatar answered Oct 09 '22 06:10

k3z