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,
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))
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):
EDIT: Note that the above method just takes a file and returns its contents - it does not take a filename, and return its contents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With