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
-
Are you using flask?Prakash Palnati– Prakash Palnati2018年05月30日 04:56:00 +00:00Commented May 30, 2018 at 4:56
-
Where are you seeing error messages? What specifically isn't working?Jonas– Jonas2018年05月30日 05:02:58 +00:00Commented May 30, 2018 at 5:02
-
action and method attribute missingSmart Manoj– Smart Manoj2018年05月30日 05:08:35 +00:00Commented May 30, 2018 at 5:08
-
also f.close() missingEvgeny– Evgeny2018年05月30日 05:17:18 +00:00Commented May 30, 2018 at 5:17
-
Yeah it was the action and method part that I was missing thanks and also the request import thanksLeptoflux– Leptoflux2018年05月30日 05:23:03 +00:00Commented May 30, 2018 at 5:23
1 Answer 1
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>