Changing values using POST method in FLASK? - python

I'm new in StackOverflow and Python. I'm trying to make a basic application where I have my < form > tag, my flask app, and my .txt. I'm trying to change values but it's not working or I don't know why it's not working. Could any of you give me a hand?
Python Flask:
from flask import Flask,render_template,flash,request,redirect
import os
app = Flask(__name__)
from lines import get_line
#app.route('/', methods=['POST'])
def change_line():
search_line= "this"
try:
for line in this.input(os.path.join(APP_STATIC, u'line.txt'),inplace=1):
if search_line in line:
x = line.replace(search_line,search_line + "\n" + request.form.get(u'this'))
print (x)
else:
print (x)
except BaseException as e:
print e
return render_template('line.html')
#app.route('/')
def showLine():
line = get_line()
return render_template('line.html', line=line)
if __name__ == '__main__':
app.run()
HTML:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Change the value of this line</title>
</head>
<body>
<form method="post" name="test">
<h4>Chaging Values with POST Method</h4>
<div class="col-sm-9">
<label class="col-sm-3 col-sm-3 control-label">I want to change : </label>
<input type="text" class="form-control" name="address" value="{{ line }}">
</div>
<input type="submit" value="Save Changes!">
</form>
My .txt file:
I want to change this.
It's returning the value of "this".
Basically when I run my app it's displaying "this" when I try to edit for "Hello" it's returning me an error:
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Line
Found! : this.
127.0.0.1 - - [21/Oct/2016 13:09:07] "GET / HTTP/1.1" 200 - global name 'this' is not defined
127.0.0.1 - - [21/Oct/2016 13:09:30] "POST / HTTP/1.1" 200 -
My output:
Please click here to see my output
I'm sorry if this is a silly question, or if this was answered before, but I've been browsing for an answer for time and I have found nothing about this, I've tried different codes but not working, been watching youtube videos and everything.
If someone know the solution would be really helpful for me.
It's for learning and Python School. Thanks!
Working on Python 2.7
EDIT
I updated code with the suggestions below but it's not working yet.
it's not overwriting my "this" with replace.
from flask import Flask,render_template,flash,request,redirect
import os
app = Flask(__name__)
from lines import get_line
import fileinput
#app.route('/', methods=['POST'])
def change_line():
search_line= "this"
try:
for line in fileinput.input(os.path.join(APP_STATIC, u'line.txt'),inplace=1):
if search_line in line:
x = line.replace(search_line,search_line + "\n" + request.form.get(u'asd'))
print (x)
else:
print (x)
except BaseException as e:
print e
return render_template('line.html')
#app.route('/')
def showLine():
line = get_line()
return render_template('line.html', line=line)
if __name__ == '__main__':
app.run(debug=True)

this.input(os.path.join(APP_STATIC, u'line.txt'),inplace=1):
should be
fileinput.input(os.path.join(APP_STATIC, u'line.txt'),inplace=1):
(you will also need import fileinput)
you need to change this because this.input doesnt mean anyhthing to python ... it has no idea what this is ...
global name 'this' is not defined
as an aside you should really run with app.run(debug=True) while developing

Related

Return button in flask

I'm learning to use Flask but I did not found a "easy solution" (by "easy solution" I mean easy for my noob level, few codes line) for this so I'm asking here for help.
How I can create a "back" button on the new generated page in flask?
This is my code:
calculator.py
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route("/")
def my_form():
return render_template("calc.html")
#app.route("/", methods=['POST'])
def my_form_post():
num_1 = request.form['Number 1']
num_2 = request.form['Number 2']
result = int(num_1) + int(num_2)
render = render_template("calc_result.html")
#return render_template("calc_result.html")
return "The result from " + str(num_1) + " plus " + str(num_2) + " is: " + str(result) + "."
app.run(host='127.0.0.1', port=5000)
calc.html
<html>
<body>
<form method = "POST">
<input name = "Number 1">
<input name = "Number 2">
<input type = "submit">
</body>
</form>
The code is working, is receiving the numbers and doing the math but the problem is, I'm not able to generate a "back" button in the new generated page with the result.
If I put for example 10 + 10 in the calc.html, I will receive:
The result from 10 plus 10 is: 20.
I would like to put a "back" button on this page or learn how to generate a new button in the new gelerated page, so I would receive something like:
The result from 10 plus 10 is: 20.
Back
Sorry the english.
Edit:
This is what user see on the first page:
What user see in first page
After put the two numbers to sum, they see:
Result page
I want allow user to come back to first page and be able to do another sum.
In both pages the link are the same: http://127.0.0.1:5000/
in your 'calc_result.html' file, make a link or button and use the 'url_for' command to bring you back to your 'calc.html' page. Flask allows you to insert Python code into your HTML via jinja templates. Check out the quickstart guide here. So:
Back
You can use the following code:
<button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script>
Please refer this.
<a href="/">
<form action="/">
<input class="btn" type="button" value="HOME" />
</form>
</a>

Basic Form In Flask Causing HTTP 400 - Python 3.5

I am new and have spent hours trying to setup a form in Flask for Python 3.5. I want the user to be able to enter a temperature setpoint and click submit button, and have the value stored in a variable.
I have this code in a template file called index.html:
<html>
<body>
<p><font size="6">Jewell Hot-Tub Controller</font>
<br>
<font size="4">Water Temperature: {{water_temp}}</p>
<br>
<font size="4">Set Point: {{set_point}}</p>
<br>
<font size="4">Enter New Set Point:</p>
<form class="form-newtemp" method="get" action="/ChangeTemp">
<input type="text" id="new_sp" name="new_sp" size="5" placeholder="New Temp." required>
<input id="1submit" type="submit">
</form>
</body>
</html>
and this code in the "flask-test.py" file:
from flask import Flask, render_template, request
app = Flask(__name__)
app.debug = True
#app.route('/')
def index():
return render_template('index.html', water_temp='12345')
#app.route('/ChangeTemp', methods=['GET'])
def process():
new = request.form['new_sp']
return 'New set point is:' + new
Entering "27" in the textbox sends the browser to a 400 Bad Request page at:
http://127.0.0.1:5000/ChangeTemp?new_sp=27
Why does this change a bad request error, rather than returning the value? The tutorials I saw used POST, but I used GET, does this require different syntax?
Also, please let me know if anything is messy, or done wrong.
Thank you!
EDIT: I also tried "request.form.get('new-sp', new)" and this causes a 500 internal server error.
multiple ways to fix your problem. i guess the fastest way is:
<form class="form-newtemp" method="post" action="{{ url_for('process')}}">
and then
#app.route('/ChangeTemp', methods=['POST])
def process():
new = request.form['new_sp']
return 'New set point is:' + new
or you can go with not changing your template and:
#app.route('/ChangeTemp', methods=['GET'])
def process():
new = request.args.get('new_sp')
return 'New set point is:' + new

Flask textarea to Python Def() [duplicate]

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 5 years ago.
Essentially what I am trying to do :
I have a simple HTML page with a Textarea to input a bunch of text, my use case is a single code on each line like below:
1234
5678
1456
etc.
Ideally I want to take that into Python and be able to work with the data and return the results. So lets start simple and say take each line as a separate entry and run it against a function to add the word "Hi" in front of it So the results are:
Hi 1234
Hi 5678
etc.
So far have this working example I found but I tend to break it anytime I try something.
Html:
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Enter some text</h1>
<form action="submit" id="textform" method="post">
<textarea name="text">Hello World!</textarea>
<input type="submit" value="Submit">
</form>
</body>
</html>
Python:
From flask import Flask, request
app = Flask(__name__)
#app.route('/')
def main_form():
return '<form action="submit" id="textform" method="post"><textarea name="text">Hello World!</textarea><input type="submit" value="Submit"></form>'
#app.route('/submit', methods=['POST'])
def submit_textarea():
return "You entered: {}".format(request.form["text"])
if __name__ == '__main__':
app.run()
Example :
i try to extract the textarea to a string and then return that back to the page with :
x = format(request.form["text"])
return x
Any help or guidance would be appreciated!
You can access and store the text from textarea with the following lines :
#app.route('/submit', methods=['POST'])
def submit_textarea():
# store the given text in a variable
text = request.form.get("text")
# split the text to get each line in a list
text2 = text.split('\n')
# change the text (add 'Hi' to each new line)
text_changed = ''.join(['<br>Hi ' + line for line in text2])
# (i used <br> to materialize a newline in the returned value)
return "You entered: {}".format(text_changed)

Import with multiple arguments: running python script in flask

I have a python script main.py that takes in two arguments (2 text files)
I'm using MAC OS X
Python 2.7
This runs easily on terminal with:
python main.py train.txt sample.txt
I have now developed a small front-end using Flask with very minor HTML as follows:
#front.py FLASK
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
#app.route('/')
def hello_world():
return render_template('index.html')
#app.route('/signup', methods = ['POST'])
def signup():
email = request.form['email']
email1 = request.form['email1']
# command below is just for testing, I wish to implement the same as this would if this would be typed in terminal.
print("main.py " + email + " " + email1)
return redirect('/')
if __name__ == "__main__":
app.run()
and the HTML
<!DOCTYPE html>
<html>
<head>
<title>T</title>
</head>
<body>
<form action="/signup" method="post">
<input type="text" name="email"></input>
<input type="text" name="email1"></input>
<input type="submit" value="Signup"></input>
</form>
</body>
</html>
This HTML code is simply using a form to take in the 2 arguments ( I find this easier than JS as I have no experience with that).
I have just written the
print("main.py " + email + " " + email1)
command above to test, it's not of any utility for now.
Usage of the parameters:
#main.py
from filter import Filter
import sys
# Get arguments from user
train = sys.argv[1]
messages = sys.argv[2]
# Open files for reading and writing
train_file = open(train, "rb")
messages_file = open(messages, "rb")
predictions_file = open("predictions.txt", "w")
# Create new filter and train it using the train-file
f = Filter()
f.train(train_file)
#filter the messages in messages_file, write results to predictions_file
f.filter(messages_file, predictions_file)
# Close all the files
train_file.close()
messages_file.close()
predictions_file.close()
I wish to now run my script which is main.py via this flask application itself, and want to know how this is possible.
I was using import main with another app decorator say /exec and manually changing the URL to go from 127.0.0.2000 to 127.0.0.2000/exec but this was giving errors as main requires the arguments to be passed.
Sorry if I'm unclear in explaining the problem, please let me know if I can explain anything in a better way to help understand the problem.
Thank you
You need to rework this script slightly. You should put all the code that deals with input inside a name == '__main__' block as you do in the Flask app, and the rest inside a function that you call from that block:
def do_stuff(train, messages):
# Open files for reading and writing
train_file = open(train, "rb")
...
predictions_file.close()
if __name__ == '__main__':
# Get arguments from user
train = sys.argv[1]
messages = sys.argv[2]
do_stuff(train, messages)
Now your Flask app can call main.do_stuff(email, email1).

Python Flask to change text in a HTML file

I'm trying to create a simple program which will replace {{ test }} with 'Hello world' by following a tutorial, however I am stumped and when I open the HTML file - as {{ test }} is shown on the page instead of 'Hello World' which is what should be appearing.
Any help would be appreciated because I am very unsure on what to do to fix this, thanks.
I am unsure if I have even linked the two files, as to my knowledge it was never specified in the video and I have only just noticed that there is no link between the two files.
Python Code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template('index.html', test='hello world')
if __name__ == '__main__':
homepage()
else:
print('Please run this file as main, not as module.')
HTML Code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<p> {{ test }} </p>
</body>
</html>
Flask is a webserver. You are not meant to call the functions with app.route. Replace the last part with:
if __name__ == '__main__':
app.run()
and then visit http://127.0.0.1:5000/ in your browser. The template file is not meant to change.
If for some reason you don't want to run a server but you just want to create HTML files, then use Jinja2, the template engine behind Flask.

Categories