I'm new to Flask and trying to build my first simple app which takes a text input and upon the user clicking a button I want it to display the text that was entered.
My HTML page loads successfully and I can enter the text into the input.
However, when I click the button I get a new page showing the following 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.
My HTML:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Predict Code</h1>
<form action="http://localhost:5000/predict" method="post">
<label form="description">Description:</label>
<input type="text" id="description" name="description">
<button type="submit">Predict Code</button>
</form>
<br>
<br>
{{ prediction_text }}
</body>
</html>
My flask app .py:
from flask import Flask, request, jsonify, render_template
# create the flask app
app = Flask(__name__)
# what html should be loaded as the home page when the app loads?
#app.route('/')
def home():
return render_template('app_frontend.html')
# define the logic for reading the inputs from the WEB PAGE,
# running the model, and displaying the prediction
#app.route('/predict', methods=['GET','POST'])
def predict():
# get the description submitted on the web page
a_description = request.form.values()
return render_template('Description entered: {}'.format(a_description))
# boilerplate flask app code
if __name__ == "__main__":
app.run(debug=True)
What have I done wrong and how can I fix it?
The problem is here:
#app.route('/predict', methods=['GET','POST'])
def predict():
# get the description submitted on the web page
a_description = request.form.values()
# THIS LINE:
return render_template('Description entered: {}'.format(a_description))
You're trying to render a template, but passing in a string, not a template.
If you want to return just the string, do this:
return 'Description entered: {}'.format(a_description)
If you look at the python error output you will see:
jinja2.exceptions.TemplateNotFound: Description entered: <generator
object MultiDict.values at 0x000001CEEEF83620>
EDIT
To answer the additional comment question. To get the value of the form post you will need to change your line from:
a_description = request.form.values()
to:
a_description = request.form.get('description')
Related
I’m new to web development. I have learned how to make a web sever using flask. What I want to do is make an html button run python code from the web server when it is clicked. Is this even possible? If so, can someone point me to some html examples that can do that?
Update: I think I found some code that might work with what I’m asking. I don’t know for sure if it would work or not.
Here is the link:
Call a python function within a html file
If I were to convert the “click a link” aspect of the code to “click a button” would it run my python code on the viewers end, not my end?
It is Possible in Two ways
Create an HTML form and button to submit the form. The from can call the post URL on the flask server
Add some javascript to the HTML and call any HTTP method /url that you have created using the flask server.
You can use button with form or with JavaScript
Form
Normally to use button you need <form> which sends request to Flask to url defined in action="..." and Flask sends back response (text/HTML) and browser automatically put it in window in place of previous HTML - so server has to generate full HTML again and again.
from flask import Flask, request, render_template_string
import datetime
app = Flask(__name__)
#app.route('/')
def index():
return render_template_string('''<form action="/page" method="POST">
<button type="submit" name="btn" value="Button 1">Button 1</button>
<button type="submit" name="btn" value="Button 2">Button 2</button>
<button type="submit" name="btn" value="Button 3">Button 3</button>
</form>''')
#app.route('/page', methods=['GET', 'POST'])
def page():
value = request.form.get('btn') # gives text from `value="Button 1"`
return f'You pressed {value} at ' + datetime.datetime.now().strftime('%Y.%m.%d %H:%M.%S')
if __name__ == '__main__':
#app.debug = True
app.run() #debug=True
And the same using empty action="" so it sends request to the same url and it needs to check request.method to run different code
from flask import Flask, request, render_template_string
import datetime
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
value = request.form.get('btn') # gives text from `value="Button 1"`
info = f'You pressed {value} at ' + datetime.datetime.now().strftime('%Y.%m.%d %H:%M.%S')
else:
info = ""
return render_template_string('''<form action="" method="POST">
<button type="submit" name="btn" value="Button 1">Button 1</button>
<button type="submit" name="btn" value="Button 2">Button 2</button>
<button type="submit" name="btn" value="Button 3">Button 3</button>
</form>{{text}}''', text=info)
if __name__ == '__main__':
#app.debug = True
app.run() #debug=True
JavaScript
If you want to execute Flask code without reloading all HTML then you need to use JavaScript which can send request to server using old
XMLHttpRequest or modern fetch(), get response and replace only part of HTML. Often in this method server sends JSON data and JavaScript may use it to replace HTML in different places.
And this method need to learn JavaScript to create something more complex.
from flask import Flask, request, render_template_string
import datetime
app = Flask(__name__)
#app.route('/')
def index():
return render_template_string('''
<button onclick="my_function()">Get Time</button>
<span id="time">Press Button to see current time on server.</span>
<script>
span_time = document.querySelector("#time");
function my_function(){
fetch('/get_time')
.then(res => res.text())
.then(text => span_time.innerHTML = text);
}
</script>
''')
#app.route('/get_time')
def time():
return datetime.datetime.now().strftime('%Y.%m.%d %H:%M.%S')
if __name__ == '__main__':
#app.debug = True
app.run() #debug=True
In examples I use render_template_string instead of render_template to make code simpler - now everyone can copy code and paste to one file and run it.
I am able to pass data from one html form to a second html page using Flask. But when I try to pass the data from the second html page to a third html page, i get an error:
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'binary'
I am basically trying to input binary numbers on the first html page, convert it to a decimal on the second html page, and then convert it to a hexadecimal number on the third page. Here is my Flask code:
from flask import Flask, redirect, url_for, render_template, request
app = Flask(__name__)
#app.route('/', methods=['POST','GET'])
def input_binary():
if request.method == "POST":
binary = request.form["binary"]
return redirect(url_for("show_decimal", bin=binary))
else:
return render_template("binary.html")
#app.route('/<bin>', methods=['POST','GET'])
def show_decimal(bin):
if request.method == "POST":
decimal = request.form["decimal"]
return redirect(url_for("show_hex", dec = decimal))
else:
decimal = int(bin,2)
return render_template("decimal.html", dec=decimal)
#app.route('/<dec>', methods=['POST','GET'])
def show_hex(dec):
hexadecimal_string = hex(int(dec))
return render_template("hex.html", hex = hexadecimal_string)
if __name__ == "__main__":
app.run(debug=True)
It seems like when i click submit on the second page again, it's trying to run the code from the def input_binary function and not the def show_hex function. Maybe it has to do with the submit button on the second page?
This is the html on the second html page:
<body>
<p>{{dec}}</p>
<form name="decimalNumber" action="." method="POST">
<label>Input the decimal number</label>
<input type="number" name="decimal">
<input type="submit" value="submit">
</form>
</body>
Any suggestions?
first, your input name "binary" may be conflicted with http protected keyname. try another name. you can see What is the cause of the Bad Request Error when submitting form in Flask application?
Below is my code. I want to convert excel file to json via my flask application. After running the code, while trying to load up the flask URL in browser, localhost gives the following error:
404 not found error - The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again
What do I need to do? Below is my application code:
from flask import Flask, request, jsonify
import flask_excel as excel
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>
<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 excel.make_response_from_array([[1,2], [3, 4]], "csv",
file_name="export_data")
if __name__ == "__main__":
app.run()
Since you've defined your app logic under the route #app.route("/upload", methods=['GET', 'POST']) and you do not have any logic defined under your base address: #app.route("/", methods=['GET', 'POST']), you have to load your application using this as your URL:
http://127.0.0.1:5000/upload
And if you are using any other host address or port number in your flask application, you have to change your URL as:
http://Your_flask_IP_Address:Port_Number/upload
Please do comment if this works. Cheers!
I'm trying to develop a simple webapp that prompts the user for their address, requests forecast information from the NWS through their API, and prints out the results, but I'm running into some issues tying together the HTML and the Python script. I'm still new to programming in general and this is all a very rough copy at the moment, here's the relevant code:
weather.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def home():
return render_template('weather.html')
#app.route('/forecast', methods=['GET', 'POST'])
def forecast():
if request.method == 'POST':
location = request.form['address']
# gets the weather information
return render_template('forecast.html', varying_forecast = forecast, wfo = wfo_info)
if __name__ == '__main__':
app.run(debug=True)
weather.html:
<form action="{{ url_for('forecast') }}" method="post">
Enter your address here: <input type="text" name="address"><br>
<input type="submit" name="submit" value="Get My Forecast!"><br>
</form>
When I try to go to 127.0.0.1:5000 I receive this error: "werkzeug.routing.BuildError: Could not build url for endpoint 'forecast'. Did you mean 'home' instead?" To the best of my knowledge this error occurs when url_for fails to find a route, but given that the forecast function does exist I'm confused where the error is coming from. Even after commenting out the form tag in the HTML the error persists. I tried getting rid of the "wfo" and "varying_forecast" in the return statement but that also didn't do anything. The only way to fix it is by setting the url_for of the action of the form to home, but I don't see any way to run the code in there and return the forecast information, considering it's already returning the home page. I'm having trouble understanding why it fails to display the weather.html page as written.
I have an HTML index page that sends input data to a python script which processes the data and outputs it in a 2nd HTML page. On a local host, the process works fine and the data is displayed as desired. But when I try to host the process online, I get an error saying the URL cannot be found. If it helps, I'm using Heroku.
Apologies in advance for any poor lingo. I only just started learning how to code recently.
1st HTML
<form action = "https://webaddress/result" method = "POST">
<h1> Enter info: </h1>
<input type="text" name="info">
<input type="submit" value="Submit"/>
</form>
Python:
from flask import Flask, render_template, request
from bs4 import BeautifulSoup
import requests
# https://doi.org/10.2118/21513-MS
app = Flask(__name__)
#app.route('/')
def student():
return render_template('Trial.html')
#app.route('/result.html',methods = ['POST', 'GET'])
def result():
return render_template("result.html",result = output)
if __name__ == '__main__':
app.run(debug = True)
The input in the 1st HTML would be sent to the python section to be broken down and rearranged (left out that part so the python code wouldn't be too long) before being output into result.html. This worked on a local host using http://localhost:5000/ and http://localhost:5000/result.
When I run it on Heroku, I get the error message:
Not Found
The requested URL /result was not found on this server.
Update: Problem solved.
Having some issues understanding your results() function. output isn't defined anywhere and type isn't used at all.
I believe your action parameter is incorrect.
Try:<form action="/result" method = "POST">
Here is a working version of what I hacked together for you:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/', methods=['GET'])
def home():
return '''
<form action="/result" method = "POST">
<h1> Enter info: </h1>
<input type="text" name="info">
<input type="submit" value="Submit"/>
</form>
'''
#app.route('/result',methods = ['POST', 'GET'])
def result():
if request.method == 'POST':
type = ''
if 'info' in request.form:
result = request.form['info']
return result
if __name__ == '__main__':
app.run(debug=True, port=8888, host='0.0.0.0')
Your form refers to /result (no .html extension), but your route is for /result.html (with the extension). Try removing the .html from your route:
#app.route('/result', methods=['POST', 'GET'])
def result():
return render_template("result.html", result=output)