Python restplus API to upload and dowload files

user3313834 picture user3313834 · Nov 11, 2016 · Viewed 10.1k times · Source

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

Answer

k3z picture k3z · Nov 11, 2016

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.