Upload, read, write excel file in Python flask - python

Im using this code which asks user to upload a file, which I want to be read into a dataframe.
Then this dataframe should be displayed as output on the page.
What should I write in the return, so as to accomplish this ?
from flask import Flask, request, jsonify
import flask_excel as excel
import pandas as pd
app=Flask(__name__)
#app.route("/upload", methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
return jsonify({"result": request.get_array(field_name='file')})
return '''
<!doctype html>
<title>Upload an excel file</title>
<h1>Excel file upload (csv, tsv, csvz, tsvz only)</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file><input type=submit value=Upload>
</form>
'''
#app.route("/export", methods=['GET'])
def export_records():
return
if __name__ == "__main__":
app.run()

I guess a barebones version of what you wanted would be this. But this would obviously require more work.
from flask import Flask, request, jsonify
import pandas as pd
app=Flask(__name__)
#app.route("/upload", methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
print(request.files['file'])
f = request.files['file']
data_xls = pd.read_excel(f)
return data_xls.to_html()
return '''
<!doctype html>
<title>Upload an excel file</title>
<h1>Excel file upload (csv, tsv, csvz, tsvz only)</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file><input type=submit value=Upload>
</form>
'''
#app.route("/export", methods=['GET'])
def export_records():
return
if __name__ == "__main__":
app.run()

Related

How to display and edit text files on the web page using python and Flask?

I want to build a simple web application based on Flask and Python for displaying and editing a text file in my directory path that I have created before on the web page. I have written the codes and can be run, but the results are not as expected. Everyone who can give me solutions is really appreciated.
from flask import Flask, request, render_template, redirect, url_for
from pathlib import Path
from os import listdir
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template('index.html')
#app.route('/', methods=['GET,POST'])
def my_form_post():
path=Path('/users/Devie Andriyani/EditFlask/days.txt') # set the path to your file here
if not path.exists():path.touch()
input_days = request.form['text_box']
if request.method == 'POST':
with open('/users/Devie Andriyani/EditFlask/days.txt', 'w') as f:
f.write(request.form.get('text_box',None))
return redirect(url_for('my_form_post'))
if __name__ == '__main__':
app.debug = True
app.run()
<!DOCTYPE html>
<head>
<title>Hello</title>
</head>
<body>
<form action="" method="POST">
<input name="text_box" value={{days}}>
<input type="submit">
</form>
</body>
</html>
And here's the result. I don't get the result as I expected. It should edit a text file
from flask import Flask, request, render_template
from os import listdir
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template('index.html')
#app.route('/', methods=['GET,POST'])
def my_form_post():
input_days = ''
if request.method == 'POST':
input_days = request.form['text_box']
with open('/users/Devie Andriyani/EditFlask/days.txt', 'w') as f:
f.write(str(input_days))
return render_template('index.html', days=input_days)
if __name__ == '__main__':
app.debug = True
app.run()
<!DOCTYPE html>
<head>
<title>Hello</title>
</head>
<body>
<form action="" method="POST">
<input name="text_box" value="{{ days }}">
<input type="submit">
</form>
</body>
</html>
I don't understand clearly what is your question but I have found some Erorrs in your code:
This is wrong
#app.route('/', methods=['GET,POST'])
you should write like this #app.route('/', methods=['GET','POST'])
also you didn't specify any element to display the days so then why you didn't see the output .
you should give some element like <p>{{days}}</p>

Read .doc file in flask api

#app.route('/parse', methods=['POST'])
def parse():
response = request.files['file']
file_name = response.filename
Wanted to save this as doc, docx, pdf or txt file. Any help appreciated.
There is a nice post that explains this in details: https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask
Here is the core.
index.html:
<body>
<h1>File Upload</h1>
<form method="POST" action="" enctype="multipart/form-data">
<p><input type="file" name="doc_file" accept=".doc,.docx"></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
app.py:
#app.route('/', methods=['POST'])
def upload_file():
uploaded_file = request.files['doc_file']
if uploaded_file.filename != '':
uploaded_file.save(uploaded_file.filename)
return redirect(url_for('index'))
# A welcome message to test our server
#app.route('/')
def index():
"""Return the main page."""
# stedin_map = get_map()
return render_template('index.html', **locals())

How to upload excel or csv file to flask as a Pandas data frame?

I have been trying to upload a csv/excel file as pandas data frame on a flask application. I am not able to find any method which could help upload the file as a data frame. Below is the code used.
from flask import Flask, request, render_template
from werkzeug import secure_filename
import pandas as pd
app = Flask(__name__)
#app.route('/upload')
def upload():
return render_template('upload.html')
#app.route('/uploader',methods = ['GET','POST'])
def uploader():
if request.method == 'POST':
#f = request.files['file']
df = pd.read_csv(request.files.get('file'))
#f.save(secure_filename(f.filename))
#df = pd.DataFrame(eval(f))
return print(df.shape)
if __name__ == '__main__':
app.run(debug = True)
You didn't provide a template you're using in your code (upload.html).
Also return print(...) returns None and None is not a valid response from a Flask view.
Here's a working example:
upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
Shape is: {{ shape }}
</body>
</html>
app.py
from flask import Flask, request, render_template
import pandas as pd
app = Flask(__name__)
#app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
df = pd.read_csv(request.files.get('file'))
return render_template('upload.html', shape=df.shape)
return render_template('upload.html')
if __name__ == '__main__':
app.run(debug=True)
dummy.csv
id,name,surname
1,John,Doe
2,Jane,Doe
Result after uploading dummy.csv:

Display Submitted Image on Redirected Page via Flask and html [duplicate]

This question already has answers here:
Post values from an HTML form and access them in a Flask view
(2 answers)
Closed 5 years ago.
I'm attempting to create a page that takes in a user-submitted image, and automatically redirects them to a new page where the image is rendered. Much of my code is borrowed from here: How to pass uploaded image to template.html in Flask. But I can't seem to get it to work; I run into a 400: Bad Request. It seems to me that the image is not saving under /static/images, but I am not sure why.
Here is the submission form in index.html:
<form method="POST" action="{{ url_for('predict') }}" enctype="multipart/form-data">
<label for="file-input" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i> Upload Image
</label>
<input name="image-input" id="file-input" type="file" align="center" onchange="this.form.submit();">
</form>
Here is my app.py code:
from flask import Flask, render_template, request, url_for, send_from_directory, redirect
from werkzeug import secure_filename
import os
UPLOAD_FOLDER = '/static/images/'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'tiff'])
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#app.route('/')
def index():
return render_template("index.html")
#app.route('/predict/', methods=['POST', 'GET'])
def predict():
if request.method == 'POST':
file = request.files['file']
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 action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
#app.route('/show/<filename>')
def uploaded_file(filename):
return render_template('classify.html', filename=filename)
#app.route('/uploads/<filename>')
def send_file(filename):
return send_from_directory(UPLOAD_FOLDER, filename)
if __name__ == '__main__':
app.run(debug=True)
And finally, I try to render it in classify.html, with the following code:
{% if filename %}
<h1>some text<img src="{{ url_for('send_file', filename=filename) }}"> more text!</h1>
{% else %}
<h1>no image for whatever reason</h1>
{% endif %}
Where am I going wrong here?
Looks like I was missing an argument in my input: name=file in index.html. Adding that fixed the error. Altogether, the input line looks like this:
<input id="file-input" name=file type="file" align="center" onchange="this.form.submit();">

Is there a simple way to process an html form upload with python?

As we all know the simplest way to upload a file in php is with this code :
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
I want a method to upload a file with python the simplest as possible, a file from the current directory like this:
import anyuploadmodule
upload(file)
Is there a such module can do this ?
There isn't anything quite that simple out there, but micro-frameworks like Flask can be lightweight and simple starting points. You'll want to checkout the documentation. Here's a snippet to get you started:
# -*- coding: utf-8 -*-
import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '/some/path/'
#app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
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 action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>'''
if __name__ == '__main__':
app.run()

Categories

Resources