Writing html form input to text file using python - 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>

Related

User input from python flask to be sent to ansible variable

Say I have an example flask app which basically is a small webform that would take in user input data called applet.py.(The code is taken from a online blog that shows an example flask app build).
from flask import Flask,render_template,request
app = Flask(__name__)
#app.route('/form')
def form():
return render_template('form.html')
#app.route('/data/', methods = ['POST', 'GET'])
def data():
if request.method == 'GET':
return f"The URL /data is accessed directly. Try going to '/form' to submit form"
if request.method == 'POST':
form_data = request.form
return render_template('data.html',form_data = form_data)
app.run(host='localhost', port=5000)
The input is captured in this below form.
<form action="/data" method = "POST">
<p>Name <input type = "text" name = "Name" /></p>
<p>City <input type = "text" name = "City" /></p>
<p>Country <input type = "text" name = "Country" /></p>
<p><input type = "submit" value = "Submit" /></p>
</form>
If I were wanting to send this received user input into ansible variables and then trigger the ansible script to run and execute the playbook based on the given variables. How can I do that? I have googled a lot around this, couldn't find a suitable example that fits my use case. (Disclaimer, not very knowledgeable about both flask and ansible, learning as I do). Appreciate help, reference and advice.
You can use the ansible_runner module to run your playbook (docs).
import ansible_runner
#app.route('/data/', methods = ['POST', 'GET'])
def data():
if request.method == 'GET':
return f"The URL /data is accessed directly. Try going to '/form' to submit form"
if request.method == 'POST':
form_data = request.form.to_dict()
r = ansible_runner.run(playbook='test.yml', extravars=form_data)
# check ansible return code
if r.rc != 0:
abort(400, 'Ansible error')
return ('', 204)
If your playbook takes some time to run you might be better adding the job of running it to a queue and processing it separately.

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>

Returning an input sentence on html with Flask and Python

I am totally new to Flask, so I am just experimenting for the moment. I simply want to read in a sentence from the user interface and then return the sentence. However, I get the error:
BadRequestKeyError(key)
My code looks as follows:
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/query', methods=['GET', 'POST'])
def do_query():
query = request.form['query']
if request.method == 'POST':
return redirect('/query')
else:
return render_template('query.html', query=query)
if __name__ == '__main__':
app.run(debug=True)
And the query.html is like this:
{% extends 'base.html' %}
{% block body%}
<form action="/query" method=”POST”>
<label> Enter your Query Sentence: </label>
<input type=”text” name=”query” id="query" >
<input type="submit" value="Submit">
</form>
<p>Here is your sentence: {{query}}</p>
{% endblock %}
I think the problem might be, that the query variable is not initialized, but I don't know how to fix it. Can anyone help me?
If you rewrite you route thus:
#app.route('/query', methods=['GET', 'POST'])
def do_query():
query = request.form['query'] if request.method == 'POST' else ''
return render_template('query.html', query=query)
You will not be trying to access non-existing request data (i.e., form data of a non-POST request). This will mean that when you first navigate to the /query page, the template will display something like:
Here is your sentence:
(i.e., no value for query)
The wrong request type issue, however, will be gone, as will the redundant redirection. Try to minimize the use of redirection, since they significantly slow down interactions, and hurt the user experience.
Solution:
The code didn't work, because I used the wrong quotes in the html file. By default, html chooses the correct quotes and (at least within PyCharm), it is not possible to make any mistakes. However, I copied the html code from a stackoverflow source. Once I fixed that, the answer provided by #Amitai Irron was working :)

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)

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