dimanche 18 juillet 2021

Process uploaded file via Flask

I have a flask app that is supposed to receive a docx or txt file from client, process it with python code and print the result to the screen. problem is, I am not sure where I should "pull" the file from.

app = Flask(__name__)
app.config['UPLOAD_PATH'] = 'C:/Users/public'
app.config['UPLOAD_EXTENSIONS'] = ['.docx', '.txt']


@app.route('/')
def upload():
    return render_template("index.html")


@app.route('/index', methods=['POST'])
def index():
    if request.method == 'POST':
        num_words = int(request.form['num_words'])
        num_beams = int(request.form['num_beams'])
        f = request.files['file']
        filename = secure_filename(f.filename)
        if filename != '':
            file_ext = os.path.splitext(filename)[1]
            # verify type of file
            if file_ext not in app.config['UPLOAD_EXTENSIONS']:
                return render_template("index.html", error="Only .docx or .txt allowed!")
            path = os.path.join(app.config['UPLOAD_PATH'], filename)
            f.save(path)
            summary = summarize(path, num_beams, num_words)
        else:  # if no file was chosen
            return render_template("index.html", error="You have to pick a file!")
        return render_template("index.html", name=f.filename, summary=summary, status="file_uploaded successfully", )

as you can see, I receive the file and immediately save it to a specific path. I save it to a specific path so that I can retrieve that path and send it to my "summary" function. There I will use "open" function to retrieve the file and process it.

app.config['UPLOAD_PATH'] = 'C:/Users/public'     
path = os.path.join(app.config['UPLOAD_PATH'], filename)
f.save(path)
summary = summarize(path, num_beams, num_words)

Unfortunately after I uploaded the app to pythonanywhere, I realized the app is not working correctly because of the save method.

How can I bypass this?




Aucun commentaire:

Enregistrer un commentaire