getting INT value from HTML form with bottlepy - python

I have a very simple peice of code which im trying to make add 2 numbers. Im quite inexperienced with python so im having a bit of trouble. Im using the bottle framework for python.
from bottle import get, post, request, run, validate
#get('/login') # or #route('/login')
def login_form():
return '''<form method="POST" action="/login">
<input name="number" type="number" />
<input type="submit" />
</form>'''
#post('/login') # or #route('/login', method='POST')
def login_submit():
name = request.forms.get('number')
intnumber = int(number)
return(intnumber + intnumber)
The trouble im having is the value returned from the textbox is a string type. So i can concatonate the two strings just fine but cannot convert them to an int to add them. It gives me the error
TypeError("'int' object is not iterable",)
when it tries to convert intnumber = int(number).
Any help on how to resolve this and why this is happening would be much appreciated.

from bottle import get, post, request, run, validate
#bottle.debug(True)
#get('/login') # or #route('/login')
def login_form():
return '''<form method="POST" action="/login">
<input name="number" type="number" />
<input type="submit" />
</form>'''
#post('/login') # or #route('/login', method='POST')
def login_submit():
number = request.forms.get('number')
intnumber = int(number)
return str(intnumber + intnumber)
run(host='localhost', port=8080)

Related

(Python) Flask - why is request.args.get returning none type [duplicate]

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 1 year ago.
I cant figure out why exactly 'request.args.get' is returning none. I take input from a form, and when the form refreshes, I expect my input there but it returns 'none' instead.
the two lines of code are
student = request.args.get('name')
grade = request.args.get('grade')
main.py:
#app.route('/')
def home():
return render_template('home.html')
#app.route('/info', method=['POST'])
def info():
student = request.args.get('name')
grade = request.args.get('grade')
return render_template('results.html', studentid=studentid, student=student,grade=grade)
home.html
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="student" placeholder="John Smith" style="width: 500px;" required>
</div>
<div class="form-group">
<label for="fgrade">Final Grade:</label>
<input type="text" class="form-control" id="fgrade" name="grade" placeholder="90" style="width: 500px;" required>
</div>
<button type="submit" class="btn btn-dark" value="Submit Form">Submit</button>
</form>
<br>
results.html
<body>
<td>{{studentid}}</td>
<td>{{student}}</td>
<td>{{grade}}</td>
Much appreciate anyone's input or help.
Because you are sending an HTTP POST request from your html page (method="POST"), so the parameters are inserted in the body of the request. To retrieve the params you need to use request.form.get("param_name")

Using '<path>' and GET forms on Flask

I have a configuration in my app that goes something like this:
#app.route("/path/<path:sub_path>", methods = ['GET'])
def path(sub_path):
print("Subpath is: " + str(sub_path))
return 1
And a form that looks something like:
<form role="form" class="" action="http://localhost:5000/path/<path:sub_path>" method="GET">
<input type="text" name="sub_path" id="sub_path" placeholder="Search 2..">
<input type = "submit" value = "submit" />
</form>
However, the print statement returns "Subpath is: <path:sub_path>".
How can I properly send the URL using the GET method?

pyFlask is putting my inputs in my url browser

Briefly, python Flask is the workbench of web hosting I use, and I am trying to create an input form that doesn't appear in your history.
This is my form html:
<form name="ViewWindow" action="/home/ViewWindow/ViewWindowResult/">
<input name="url" type="url" required="required" placeholder="URL Here">
<input type="submit" value="Go">
</form>
And this is the python code working with the input url:
#web_site.route('/home/ViewWindow/ViewWindowResult/', methods=('GET', 'POST'))
def ViewWindowResult():
urlboi = request.values.get('url')
response = urllibrequest.urlopen(url) # import urllib.request as urllibrequest
htmlBytes = response.read()
htmlstr = htmlBytes.decode("utf8")
return html("ViewWindowResult.html", value=htmlstr)
My goal is to get here; /home/ViewWindow/ViewWindow/ViewWindowResult/,
but I end up getting here when I input "https://www.w3schools.com/tags/"; /home/ViewWindow/ViewWindowResult/?url=https%3A%2F%2Fwww.w3schools.com%2Ftags%2F
Why does Flask put my inputs in the url string? I do not intend to do this anywhere.
Edit: You can check this out by going to https://sm--supermechm500.repl.co/home/ViewWindow/
Try specifying the form method like so:
<form name="ViewWindow" action="/home/ViewWindow/ViewWindowResult/" method="post">
<input name="url" type="url" required="required" placeholder="URL Here">
<input type="submit" value="Go">
</form>
use post method like
<form name="ViewWindow" action="/home/ViewWindow/ViewWindowResult/" method="post">
<input name="url" type="url" required="required" placeholder="URL Here">
<input type="submit" value="Go">
</form
and then you python code is
#web_site.route('/home/ViewWindow/ViewWindowResult/', methods=('GET', 'POST'))
def ViewWindowResult():
input=request.form['url']
#write your code here
return(input)
its working for me it will print the url which same you entered

Python Flask/JSON Error: Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)

guys.
So my problem is as follows.
I created a linear model and saved it as .pkl in Python 3.7.
Then, I created an app.py file with the code shown below (html template file is also created).
import pickle
from flask import Flask, request, render_template, jsonify
#creating instance of the class
app=Flask(__name__)
#loading the model
model = pickle.load(open("model.pkl", "rb"))
#loading the index template and the main page
#app.route('/')
def index():
return render_template('index.html')
#inputs from the user
#app.route('/result', methods=['POST'])
def result():
features = request.get_json(force=True)['Input1', 'Input2', 'Input3',
'Input4', 'Input5', 'Input6',
'Input7', 'Input8', 'Input9']
#creating a response object
#storing the model's prediction in the object
response = {}
response['predictions'] = model.predict([features]).tolist()
#returning the response object as json
return flask.jsonify(response)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000, debug=True)
The problem is that, when I run app.py file, I get this error: "Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)". I tried modifying my code multiple times, even trying to find another solution to write it, but no luck so far, it just always raises an error.
Is there any mistake in my code that may raise this error? I should note (if it may be important) that all my variables are float type except one which is an integer.
The html script is included here as follows:
<html>
<body>
<h3>Prediction_form</h3>
<div>
<form action="{{ url_for('result') }}" method="POST">
<label for="Input1">Input1</label>
<input type="text" id="Input1" name="Input1">
<br>
<label for="Input2">Input2</label>
<input type="text" id="Input2" name="Input2">
<br>
<label for="Input3">Input3</label>
<input type="text" id="Input3" name="Input3">
<br>
<label for="Input4">Input4</label>
<input type="text" id="Input4" name="Input4">
<br>
<label for="Input5">Input5</label>
<input type="text" id="Input5" name="Input5">
<br>
<label for="Input6">Input6</label>
<input type="text" id="Input6" name="Input6">
<br>
<label for="Input7">Input7</label>
<input type="text" id="Input7" name="Input7">
<br>
<label for="Input8">Input8</label>
<input type="text" id="Input8" name="Input8">
<br>
<label for="Input9">Input9</label>
<input type="text" id="Input9" name="Input9">
<br>
<input type="submit" value="Submit">
<br>
<br>
{{ prediction_text }}
</form>
</div>
</body>
</html>
I am new to Python, so I may be missing something important.
Any help is appreciated.
Many thanks.
The form post uses the default encoding of application/x-www-form-urlencoded. That's not compatible with using get_json() to retrieve the posted form. Setting up your data for prediction will require something like this
form_fields = ['Field1', 'Field2' ... and so on ]
features = [request.form[field] for field in form_fields]
instead.

Python Flask render_template returns HTML script instead of redirecting to the HTML page

I have a Python script that uses Flask web framework to let users ask a question and depending on some certain questions, the application should ask back some questions to the user on a second webpage. The answers to the questions are evaluated based on the questions and displayed on the initial webpage.
model.py
### Importing Flask ###
from flask import Flask, render_template, request, session, redirect, url_for
### Initializing Flask ###
app = Flask(__name__)
#app.route('/')
def index():
return render_template('init.html')
#app.route('/handle_data', methods = ['POST', 'GET'])
def handle_data():
### User Inputs Question ###
userQuestion = request.form['userQuestion']
def model():
message = "Depends on User"
if message == "Depends on User":
return render_template('user_information.html', userQuestion = userQuestion)
else:
message = "Your answer is ABC."
return message
message = model()
return render_template('init.html', userQuestion = userQuestion, message = message)
#app.route('/user_information', methods = ['POST', 'GET'])
def user_information():
userLevel = request.form['userLevel']
userDOJ = request.form['userDOJ']
userType = request.form['userType']
message = "Answer for Eligibility."
return render_template('init.html', userLevel = userLevel, userDOJ = userDOJ, userType = userType, message = message)
if __name__ == '__main__':
app.run()
These are my two HTML files:
init.html (initial webpage)
<!DOCTYPE html>
<html>
<head>
<title>Human Resources</title>
<!-- for-mobile-apps -->
</head>
<body>
<div class="main">
<div class="w3_agile_main_grid">
<h2>Human Resource Portal</h2>
<br>
<p>Hi</p>
<form action="{{ url_for('handle_data') }}" method="post" class="agile_form">
<input type="text" name="userQuestion" placeholder="Ask your question..." required="">
<input type="submit" value="Submit">
</form>
<p>{{ message }}</p>
</div>
</div>
</body>
</html>
user_information.html (second webpage)
<!DOCTYPE html>
<html>
<head>
<title>Human Resources</title>
</head>
<body>
<div class="main">
<div class="w3_agile_main_grid">
<h2>Human Resource Portal</h2>
<form action="{{ url_for('user_information') }}" method="post" class="agile_form">
<!--<input type="text" name="userName" placeholder="Enter your name." required="">-->
<input type="text" name="userLevel" placeholder="What is your level?" required="">
<input type="text" name="userDOJ" placeholder="What is your date of joining?" required="">
<input type="text" name="userType" placeholder="Are you on sabbatical or specialist?" required="">
<input type="submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
When I execute my script and enters a question, what I get is the HTML code for user_information.html as my answer which is not what I want.
Ouput after I click Submit:
https://ibb.co/cwhRpk
Expected output after I click Submit:
https://ibb.co/c7CFh5
https://ibb.co/dX9T25
I can get the desired output if I remove the model() construct but that will make my code inefficient because in my actual application I have to call model() multiple times with different parameters.
Can anyone please suggest me what approach should I take? I'm totally stuck in this part. Thanks, any help is appreciated!
Your nested model() function does not make any sense at all. It returns the result of render_template, which is a complete response including HTTP headers etc. If you try and insert that into another template, Jinja will be forced to try and convert it to a string, which gives the result you see.
This is not at all the way to compose templates. Jinja supports template inheritance; you should call render_template once only, using a child template that inherits from a common base.

Categories