Reputation: 43
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
Upvotes: 0
Views: 3319
Reputation: 4551
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>
Upvotes: 1