Logical Mistakes using Flask, CSV files and HTML-forms [duplicate] - python

This question already has answers here:
How to debug a Flask app
(14 answers)
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 4 years ago.
So, what I want to do is read 2 csv files, send them over my app.py and then print the results in a new HTML using Flask. Problem is, I can't find what I'm doing wrong. To be more specific I'm sending my CSV files through my app.py and I get either internal errors (500) or server errors (404) one after the other and I don't have a syntax error so it MUST be logical. So, what can I do to fix that because I'm at square one and my gut says that is as trivial as they come.
app.py:
from flask import Flask, render_template, request
import numpy
import pandas
import jinja2
app = Flask(__name__)
#Create a route to a file which is called "/" and uses both GET and POST
#app.route('/', methods=['GET', 'POST'])
#define function send
def results():
#retrieve data from form where we used POST
if request.method == 'POST':
table1=request.files['table1']
table2=request.files['table2']
#define function
def new_t(t1,t2):
#Combine t1 and t2
t3=np.hstack((t1,t2))
return(t3)
results=new_t(t1,t2)
#sends input to the template results.html with the inherited value "results"
return render_template('/results.html', results=results)
#in case there was a mistake we are redirecting the user to index.html
return render_template('/index.html')
index.html:
<!DOCTYPE html>
<html>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<body>
<h1>Give to your CSVs: </h1>
<!-- Create a form that sends data to our server (in this case local) using POST method -->
<form method="POST" action="/results" enctype="multipart/form-data" >
<!-- Style our input using Bootstrap CSS -->
<div class="form-group">
<!-- Create an input with type text so we can type our age in text form -->
<b>Choose Table1 (CSV format):</b>
<input type="file" name="table1">
<b>Choose Table2 (CSV format):</b>
<input type="file" name="table2">
</div>
<!-- Create and style our submit button-->
<input class="btn btn-primary" type="submit" value="submit">
</form>
</body>
</html>
results.html
<!DOCTYPE html>
<html>
<header>
</header>
<body>
<!-- Print out the age that we typed which was sent from our app.py -->
<h1>Results: </h1>
<table>
{{ results|safe }}
</table>
</body>
</html>

Related

Load file selected in html page to pandas

I am trying to automate the Winross(market research tool) tables syntax to generate Open-end tables. I need to use two excel files for this for which I am planning to use Pandas. I am not sure how to load the excel files into pandas which are selected in HTML using input type = "file".
Adding both HTML and python codes below
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>OE Tables</title>
</head>
<body>
<form class="" action="getfile" method="post" enctype="multipart/form-data">
<h1>OE Tables Generator</h1>
<h3>Select OE data:</h3>
<input type="file" name="myfile" value=""><br><br>
<input type="submit" name="" value="Upload OE File"><br><br>
<h3>Select Code-frame:</h3>
<input type="file" name="myfile" value=""><br><br>
<input type="submit" name="" value="Upload Code-frame"><br <br>
</form>
</body>
</html>
from flask import Flask, render_template, request
import pandas as pd
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route('/getfile', methods=['GET', 'POST'])
def getfile():
if request.method == 'POST':
excel_file = request.files['myfile']
oedata = pd.read_excel(excel_file)
return oedata.head()
else:
result = request.args.get['myfile']
return result
Currently getting a page with below error:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

Passing HTML variable to use in python function

I am trying to pass an input variable in a form tag to use in a python function. However, I keep getting different HTTP errors. I have changed the code numerous times drawing reference from other questions on the stack, none of them have worked.
The problem seems to be with the URL, the input variable appears in the URL but I may not be handling it correctly. I'm also getting an error sometimes with the 'attempted_question' not being recognized.
Any help appreciated
index.html
<html>
<head></head>
<body class = "body">
<body>
<form action="{{ url_for('about') }}" method=”PUT”>
<label> Enter population based question: </label>
<input name = "pop_question" >
<button type=”submit”> Submit </button>
</form>
<p> </p>
</body>
</body>
</html>
pass.html
<html>
<head></head>
<body class = "body">
<body>
<p> i am here {{ attempted_question }}</p>
</body>
</body>
</html>
</html>
run.py
from flask import Flask, render_template
#app.route("/")
def hello():
return render_template("index.html")
#app.route("/about", methods=['GET'])
def about():
living = request.form['pop_question']
return render_template('pass.html', attempted_question=living )
if __name__ == "__main__":
app.run(debug=True)
You use different http methods when sending and receiving data.
Try to use same method. 'POST' for example.
index.html
...
<form action="{{ url_for('about') }}" method=”POST”>
...
run.py
...
#app.route("/about", methods=['POST'])
...

Process JSON reply from flask server in javascript and display the returned value in HTML [duplicate]

This question already has answers here:
How to get POSTed JSON in Flask?
(13 answers)
jQuery posting JSON
(3 answers)
Closed 5 years ago.
I have seen similar posts (which is how i have arrived at this current implementation) however i cannot get the below code to work. I want to:
Receive input from the user (badge id)
POST to the flask webserver via ajax
process the badge id and send back the result
receive the reply and process via javascript to be outputted via HTML onto the screen.
What is currently happening:
500 error TypeError: 'NoneType' object is not subscriptable.
When i use postman to submit a JSON to flask the reply works perfectly.
index.html
<!DOCTYPE html>
<html>
<head>
<title>App</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.4.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="{{ url_for('static', filename='form.js') }}"></script>
</head>
<body>
<div class="container">
<br><br><br><br>
<form class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="badge" name ="badgeinput" placeholder="Badge Scan..">
<button type="submit" class="btn btn-default">Submit</button>
<br>
<br>
<div class="container">
<span name="result" id="result">... </span>
</div>
</div>
</form>
<br>
</body>
</html>
form.js:
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data : {
badge_ID: $('input[name="badgeinput"]').val(),
},
type : 'POST',
url : '/process'
})
.done(function(data) {
document.getElementById('#result').innerHTML = data.result;
});
event.preventDefault();
});
});
Flask:
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/process', methods=['POST'])
def process():
badge = request.json['badge_ID']
one = "Test"
new_badge_id = badge + one
return jsonify({'badge_ID' : new_badge_id})
if __name__ == '__main__':
app.run(host="localhost", port=4000, debug=True)
I'd say it's your input that is the problem.
You should have a check if request.json['badge_ID'] has any value.
You could also use developer tools (F12) in your browser to verify that the data you're sending is correct, checking post header in the network tab.
You haven't specified your post data-type, so it's better to consider it as being form not JSON.
you could set the type to post and be a bit safe about not getting data using :
request.form.get('badge_ID', None)
then, it seems that you have a typo in your jquery.done part.
return jsonify({'badge_ID' : new_badge_id})
since your result is
{"badge_ID": new_badge_id}
you don't have any data.result and you should try data.badge_ID
since in your comment you mentioned that you don't have None badge_ID in your view, so there is a good chance that changing this part in your code would fix it.
PS:
i would change your JS code to Jquery like this:
$("#result").html(data.badge_ID);
but your own JS should work just fine.

Flask submit form and show inserted values

I am completely new to python and Flask and I am trying to run in my computer the code showed in this page:
http://runnable.com/UhLMQLffO1YSAADK/handle-a-post-request-in-flask-for-python
This are the steeps I follow and the code:
1-I have installed Flask
2-Files
File app.py
# We need to import request to access the details of the POST request
# and render_template, to render our templates (form and response)
# we'll use url_for to get some URLs for the app on the templates
from flask import Flask, render_template, request, url_for
# Initialize the Flask application
app = Flask(__name__)
# Define a route for the default URL, which loads the form
#app.route('/')
def form():
return render_template('form_submit.html')
# Define a route for the action of the form, for example '/hello/'
# We are also defining which type of requests this route is
# accepting: POST requests in this case
#app.route('/hello/', methods=['POST'])
def hello():
name=request.form['yourname']
email=request.form['youremail']
return render_template('form_action.html', name=name, email=email)
# Run the app :)
if __name__ == '__main__':
app.run(
host="0.0.0.0",
port=int("80")
)
File form_action.html
<html>
<head>
<title>Handle POST requests with Flask</title>
<link rel=stylesheet type=text/css href="style.css">
</head>
<body>
<div id="container">
<div class="title">
<h1>POST request with Flask</h1>
</div>
<div id="content">
Hello <strong>{{name}}</strong> ({{email}})!
</div>
</div>
</div>
</body>
</html>
File form_submit.html
<html>
<head>
<title>Handle POST requests with Flask</title>
<link rel=stylesheet type=text/css href="style.css">
</head>
<body>
<div id="container">
<div class="title">
<h1>POST request with Flask</h1>
</div>
<div id="content">
<form method="post" action="{{ url_for('hello') }}">
<label for="yourname">Please enter your name:</label>
<input type="text" name="yourname" /><br />
<label for="youremail">Please enter your email:</label>
<input type="text" name="youremail" /><br />
<input type="submit" value="Send" />
</form>
</div>
</div>
</div>
</body>
</html>
3-I run the py file:
sudo python app.py
[sudo] password for jose:
* Running on http://0.0.0.0:80/ (Press CTRL+C to quit)
When I open the browser I write:
file:///home/jose/Escritorio/python/app/form_submit.html
I insert the data in the 2 forms and I press Send and this is what happens:
URL: file:///home/jose/Escritorio/python/app/{{url_for('hello')}}
Web Page: File not found
What am I doing wrong?
0.0.0.0 means that you can access the flask website from outside of the website host. Use the host ip plus the port # you specified
http://:80/hello in your case. That should display the form_action.html you specified in your routes.
If you want save form data, your code didn't work. You must have a database or save in a file.

String literals are truncated using flask in python 3.4

When I run the following simple piece of python / flask I do not get the entire string passed through to the html page - instead of "hello this is simon" I get "hello"
I am working on Python 3.4.2
I thought it might be something to do with encoding but I have tried everything I can think of with encoding and still no joy. Any help gratefully received :)
This is the python file (testit.py)
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def init_logon():
email = "hello this is simon"
return render_template("testit.html", email=email)
if __name__ == '__main__':
app.debug = True
app.run()
This is the simple template (testit.html)
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email" value={{ email }}>
</p>
</body>
</html>
The out put from a number of browsers is all the same: the text is truncated at the first white space
All that is displayed in my browser is:
"hello" - none of the text after the first white space is passed through
apologies I am not allowed to post the image I created :(
In your HTML, you didn't quote the attribute value, so the result of your template is
<input type="text" name="email" id="email" value=hello this is simon>
That means only the "hello" is the value of the "value" attribute. You should be able to see this if you look at the source of the generated page.
You could change your template so it has value="{{ email }}".

Categories