Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful API with python and flask to request and read a text file

I am trying to read a text file using flask framework. This is my code

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


app = Flask(__name__)


@app.route('/index', methods=['GET'])
def index():
    return 'Welcome'

@app.route('/getfile', methods=['POST'])
def getfile():
    file = request.files['file']
    with open(file,'r') as f:
        file_content = f.read()
    return jsonify(file_content)    

if __name__ == '__main__':
    app.run(host = '0.0.0.0')

I am using POSTMAN to check it, pic

unfortunately it sends bad requests 400. I requested file as request.file. The .txt is residing in my disk at C:/Users/rbby/Desktop/Programs/hello.txt

The GET method is working fine. POST is not working for me. Is there anything else i should add from my above code?

I referred to this link Using Flask to load a txt file through the browser and access its data for processing Do i need to add these lines too? I don't understand these

filename = secure_filename(file.filename) 

# os.path.join is used so that paths work in every operating system
file.save(os.path.join("wherever","you","want",filename))
like image 688
Jonreyan Avatar asked Sep 03 '25 09:09

Jonreyan


1 Answers

Assuming that what you want POST /getfile to do is return the contents of the text file, then you can simply define your getfile() function as:

def getfile():
    file = request.files['file']
    return file.read()

Also make sure in Postman that you are setting the key of your file to file (as in the screenshot below):

Postman screenshot, with key set to file

EDIT: Note that the above method just takes a file and returns its contents - it does not take a filename, and return its contents.

like image 160
Ollie Avatar answered Sep 04 '25 23:09

Ollie