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

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>

Related

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

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.

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.

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)

Writing html form input to text file using python

I'm trying to use this code to print a number from a html form to a text document for storage but it doesn't seem to be working
#app.route("/result",methods = ['POST', 'GET'])
def result():
if request.method == 'POST':
timer = request.form['timer_input']
f = open("timer.txt", "w")
f.write("Water every {} days".format(timer)
templateData = template(text = "timer")
return render_template('timer.html', **templateData)
<form>Set frequencys (e.g. 2 = every 2 days): <br>
<input type ="number" name="timer_input">
<br>
</form>
does anyone know why it's not working? I've looked at several places for alternatives but they all use cgi or php and I'm not interested in using either
Even though your initial problem looks solved, here are several bits of suggestions:
It is more typical for one address (view) to display a form and another
address to showswhat the result is when form is completed.
File write operation looks more secure as a separate function. You need to close the file, or better use with.
You do nothing on GET, so the function can be simplified.
Here is the code with these ideas in mind:
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('timer.html')
#app.route("/result", methods= ['POST'])
def result():
timer = request.form['timer_input']
log_message = "Water every {} days".format(timer)
screen_message = "Sure, will water every {} days!".format(timer)
save(log_message)
return screen_message
def save(text, filepath='timer.txt'):
with open("timer.txt", "w") as f:
f.write(text)
app.run()
templates/timer.html:
<html><body>
<form action = "result" method = "POST">
Set frequencies (e.g. 2 = every 2 days):
<br>
<input type ="number" name="timer_input">
<input type = "submit">
<br>
</form>
</body></html>

Use flask to receive data from form

I am trying to use flask to get data from a html form. The form shows up on the website ok, but when I submit python doesn't receive it.
Html code:
<form action="/signup" method="post">
<input type="text" name="email"></input>
<input type="submit" value="signup"></input>
</form>
Python code:
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/about/')
def about():
return render_template('about.html')
#app.route('/signup', methods = ['POST'])
def signup():
email = request.form['email']
print("The email address is '" + email + "'")
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)
APP
--static
----main.css
--templates
----html code(home.html)
python code(hello.py)
The code works fine for me.
The only thing I would change is using the url_for() construct instead of directly specifying your endpoints.
I.E.: use return redirect(url_for('home'))
Alternatively, try to provide a GET request for your 'signup' endpoint.
Add 'GET' to your methods argument
Put your printing block under an if statement (if request.method == "POST")
Underneath this block put something to return. (return redirect(url_for('home')), return render_template('xyz.html'), etc.)

Categories

Resources