2

I want to create a REST API using Flask. I have two files at any given time, I will call my API and send these two files, a python script will run on the API side and send me back a JSON Response. Now this is the overall idea of my application , but I don't know how to do all this. As I do not want to save those two files, just take them as an Input and send the result back, I don't think i will need to save the files. But I do not know how to send files to the API, logic part is ready, I just need to know how to send two files, process them and send back the response in just one API call. Thanks in advance

I have just setup the basic API till now.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Server works'


if __name__== '__main__':
    app.run(debug=True)

2 Answers 2

7

Found this on the Flask documentation:

import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''

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.

    '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''

In this example, the backend is saving the uploaded files to UPLOAD_FOLDER. This example is also using some exception handling to make sure that the user is uploading the correct type of file types.

[EDIT] I misread your question. If you just want to send back a JSON response instead of JSON containing the files content you would do this:

return jsonify({"response": "success"})

Finally, here's a link to the full Flask documentation

Sign up to request clarification or add additional context in comments.

Comments

0
from flask_restx import Resource, fields
from flask import request
import sys
import os
from werkzeug.datastructures import FileStorage
from werkzeug.utils import secure_filename   

BASEDIR = os.path.abspath(os.path.dirname(__file__))

upload_parser = api.parser()
upload_parser.add_argument('file', location='files',
                               type=FileStorage, required=True) 

@api.route("/your_route_name")
@api.expect(upload_parser)
class MyResource(Resource):
    @api.marshal_with(<output_dataformat_schema_defined_here>, skip_none=True)
    def post(self):
       uploaded_file = request.files['file']

       if uploaded_file:
          secured_uploadedfilename = 
                    secure_filename(uploaded_file.filename)
          uploaded_file.save(os.path.join(os.path.join(BASEDIR, 
             "your_foldername"), secured_uploadedfilename))
          return {"message": "File successfully uploaded"}
       else:
          return {"message": "File upload unsuccessful"}

Source: Flask restx, Flask

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.