displaying flask input() to a html template [duplicate] - python

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 12 months ago.
how can i display an input to my web application? Ive tried many ways but not succesfully...
import random
import re
from flask import Flask, render_template
app = Flask(__name__)
app.debug = True
#app.route("/")
def index():
return render_template("play.html")
#app.route("/hangman")
def hangman():
answer = input("Hi, wanna play? Y/N: ")
return render_template("game.html", answer=answer)

In game.html template you should put an input tag:
<form method="post" action="/want-to-play">
<input type="text" placeholder="Do you want to play?" />
<input type="submit" value="OK"/>
</form>
Then just put an endpoint /want-to-play in your flask app with what you want to do.

Related

Python Flask: How to save the data from page [duplicate]

This question already has answers here:
Insert or write data to .txt file with flask
(2 answers)
Closed 1 year ago.
Is anyone wrapping up flask in python well? I have a registration form but I don't know how to save the data from that page, like name and password, so I can read it later.
Save to a separate file of type:
file = open(file.txt)
file.write(username + password)
does not work when I already host the page.
Firstly, can you provide your code? What would you like to create? Is it a simple web application that requires registration and authorization or is it just a form from which you would like to take some data?
Secondly, there is some good tutorials in the Internet about Flask registration. Moreover, you can read this. Here there is a Flask student book. You can search for something different if this tutorial will not actual and proper for you.
Thirdly, about saving data in the textual file .txt from flask app. You can check this answer.
UPD. For the last variant with file.
app.py
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/', methods = ['POST'])
def get_data():
login = request.form['login']
password = request.form['password']
if request.method == 'POST':
with open('data.txt', 'a+') as f:
f.write(str(login) + ' ' + str(password) + '\n')
return render_template("index.html")
if __name__ == '__main__':
app.run(debug = True)
templates/index.html
<html>
<body>
<form action="" method="POST">
<p>Login <input name="login" /></p>
<p>Password <input name="password" /></p>
<p><input type="submit"></p>
</form>
</body>
</html>

How do I make an HTML button execute python code onclick?

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.

Python flask - change template when a button is clicked [duplicate]

This question already has answers here:
TypeError: 'dict' object is not callable
(8 answers)
Get the data received in a Flask request
(23 answers)
Closed 2 years ago.
I want to change templates when a button is clicked.
Here is my python code:
#app.route("/", methods = ['POST', 'GET'])
def my_forum_post():
if request.method == 'POST':
if request.form['myBtn'] == 'Sign in':
return render_template('new_profile.html')
And here is my HTML code:
<form method = 'POST'>
<input type="button" name="myBtn" value="Sign in">
</form>
And the template which i want to swich to is called: new_profile.html
The problem is with this line of your code:
text = request.form('input')
Change it to this:
text = request.form['input']
or this
text = request.form.get('input')

Internal server error when clicking button in flask app

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')

Having trouble sending data from html to python using flask

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)

Categories

Resources