Flask - Creating dynamic URL based on user input - python

I'm trying to create a dynamic URL based on user's input from an HTML form.
For example, if a user types in 'AAPL' or 'KO', the next page should be:
webapp.com/result/AAPL or webapp.com/result/KO
index.html:
<div class="cell" id="cell-1-2">
<span class="data" style="text-align: center;">
<form action="{{ url_for('ticker_result', variable='variable') }}" method="POST">
<input type="text" name="variable" placeholder="search ticker or company" maxlength="4"
font-size="24px" style="text-transform:uppercase">
<input class="button" type="submit" value="Search" onclick="tickerSymbol();">
</form>
</span>
</div>
I've tried renaming the 'variable' part to several different things and nothing works so I'm just stuck at this point.
main.py:
# Routing to the homepage
#app.route("/")
def markert_hours_today():
return render_template(
"index.html")
# Routing to the result page
#app.route("/result/<variable>", methods = ["GET", "POST"])
def ticker_result(variable):
if request.method == "POST":
result = request.form["variable"]
return render_template(
"result.html",
result=result)
When I run the local environment, and type in a ticker symbol, the next URL is:
webapp.com/result/variable
I'm assuming it's HTML that I need to edit? I've read the quickstart documentation for Flask which isn't making sense to me and looked up similar questions but I can't seem to find an answer to this.

You are coming at it from the wrong way. When Jinja creates index.html based on your template you can't know what variable is going to be, so how is Jinja supposed to know?
What you need to do is send the form back to the same route and then redirect the user to whatever they typed in. So something like this:
from flask import request, redirect, url_for
#app.route("/", methods=['GET', 'POST'])
def markert_hours_today():
if request.method == 'POST':
result = request.form['variable']
return redirect(url_for('ticker_result', variable=result)
return render_template("index.html")
Edit: forgot to rename variable from user_input to result.

Related

reload my web page with my data after get value from a form in Flask

I have an html web page. I analyze a sample data and send related plot and table contents to my web page and show them. In the same page I have a text area to get parameter of my next task. after getting the parameter from user, I should do rest of analyze and show another plot and table in the same page. As a result I should have a page like this:
I have app.py (this is part of my code):
#app.route('/', methods=["GET", "POST"])
def index():
tsk1_image = get_from_function_1(data)
tsk2_table_content = get_from_function_2(data)
return render_template('index.html', tsk1_img=tsk1_image, tbl=tsk2_table_content)
and I have index.html (specifically the part of the form is here):
<form action="{{ url_for('index') }}" class="form" method="post" >
<label for="value_k">K:</label>
<input type="text" id="value_k" name="value_k" placeholder="Enter k..." onClick="writeOut()">
<button type="submit" class="btn btn-primary btn-block btn-large">submit!</button>
</form>
Now I want to reload my page with all of data and parameter again and have the final result. I've wrote this part of code but it doesn't work.
if request.method == "POST":
k = request.form.get("value_k")
return redirect(url_for('index'))
Actually I should render_template('index.html', tsk1_img=tsk1_image, tbl=tsk2_table_content, tsk3_img=tsk3_image, tbl2=tsk4_table_content) after I get the value, but I don't know what should I do...
If the page is reloading but not with the data you need, that is because index() is just recalculating the data the same way each time. index() should have a check for if the request is a post, and then if so, use that data in the functions you have. Here's the idea:
#app.route('/', methods=["GET", "POST"])
def index():
my_var = default_value_here
if request.method == 'POST':
my_var = request.form.get("value_k")
tsk1_image = get_from_function_1(data, my_var)
tsk2_table_content = get_from_function_2(data, my_var)
return render_template('index.html', tsk1_img=tsk1_image, tbl=tsk2_table_content)
This way your form data will be used when you reload the data.

What's wrong with this Flask request? [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 have been working with flask for a long while, but after a break from it, I cant seem to figure out what's wrong here.
index.html:
<input name="linkHolder" type="url" class="defaultTextBox advancedSearchTextBox link" placeholder="http://www.youtube.com">
<form method="POST" action="/button">
<input class="btn" type="submit">Go</input>
</form>
main.py:
#app.route('/button', methods=["GET", "POST"])
def button():
if request.method == "POST":
dlink = request.form.get("linkHolder")
print(dlink)
return render_template("index.html", dlink=dlink)
I'm sorry if its a simple answer but my end goal here is to load the link typed by the user, print said link, and then reload the page. What am I doing wrong?
In your index.html, your <form> tag does not include the linkHolder input.
Do the following:
<form method="POST" action="/button">
<input name="linkHolder" type="url" class="defaultTextBox advancedSearchTextBox link" placeholder="http://www.youtube.com">
<input class="btn" type="submit">Go</input>
</form>
You might also need an if statement in main.py that actually renders the page
#app.route('/button', methods=["GET", "POST"])
def button():
if request.method == "GET":
return render_template("index.html")
if request.method == "POST":
dlink = request.form.get("linkHolder")
print(dlink)
return render_template("index.html", dlink=dlink)
You need a form with the name
Also, your tag </input> input doesn't have any closing tag you should be using button tag
<form method="POST" action="/button">
<input type="text" name="linkHolder">
<button class="btn" type="submit">Go</button>
</form>

404 not found "requested URL was not found"

I'm trying to make a button in sida2 take me to resultat and post the information named MJ from the input form but I get an error 404 The requested URL was not found on the server and I don't understand why. This is the html part:
<form action="/sida2/resultat.html" method="POST">
<input title="" placeholder="MJ/kq foder" type="text" name="MJ" required>
<br>
<button type="submit">Submit</button>
</form>
And this is the python part:
from flask import Flask, render_template, request
app=Flask(__name__)
#app.route('/')
def home():
return(render_template("hemsida.html"))
#app.route('/sida2/', methods=['POST', 'GET'])
def sida2():
return(render_template("andrasidan.html"))
#app.route('/sida2/resultat', methods=['POST'])
def resultat():
if request.method=='POST':
mj= request.form["MJ"]
return(render_template("resultat.html"))
if __name__ =="__main__":
app.run(debug=True)
I assume it's something obvious I'm missing but I just can't seem to find it.
Use url_for to generate URLs to Flask views. The view you want is resultat.
<form action="{{ url_for('resultat') }}" method="POST">
This will generate the appropriate URL for your resultat() function:
#app.route('/sida2/resultat', methods=['POST'])
def resultat():
The URL you currently have in your form action (/sida2/resultat.html) will not work as your code binds to the URL /sida2/resultat instead.
For a quick overview of the benefits of why you should use url_for over hardcoding your URLs, check out the Flask quickstart section on the topic.

Append HTML Radio button options to Python Flask URL

I've looked around but can't seem to find an answer. I've an html form with radio button options in it. I'm trying to append them to the flask url when the results are posted based on the user input on the html page.
Here is my html page:
<form class="form-search" id="formdata" action="{{url_for('users')}}" method="post">
<label><font size="4">Select option:</font></label>
<div class="labeltext btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="radioOptions" id="option1" value="Option1" checked> Option1 </label>
<label class="btn btn-primary">
<input type="radio" name="radioOptions" id="Option2" value="Option2"> Option2 </label>
</div>
</form>
My Flask View:
#app.route('/users/<selectOption>', methods=['GET', 'POST'])
def users(selectOption):
if request.method == 'POST':
radioOptions = request.form['radioOptions']
return redirect (url_for('users', selectOption=selectOption))
return render_template('users.html')
I'm ending up with error
TypeError: users() takes exactly 1 argument (0 given)
Unsure what's going wrong from my end. I'm trying to make my url something look like below:
localhost:8080/users?radioOptions=Option1
TypeError: users() takes exactly 1 argument (0 given)
The above error you get explains it all. In the following code :
if request.method == 'POST':
radioOptions = request.form['radioOptions']
return redirect (url_for('users', selectOption=selectOption))
You redirect to users while submitting the radio option.The users expects an argument which you have not provided yet ,i.e it is changeable and that is why you are getting this error.Plus you are also not using your radioOptions value which you retrieve from this line
selectOption = request.form['radioOptions'] #I have changed radioOptions to selectOption
The correct and cleaner way would be to define another function which renders your template and call it then in your redirect call , something like this :
#app.route('/users', methods=['GET', 'POST'])
def users():
if request.method == 'POST':
selectOption = request.form['radioOptions']
return redirect (url_for('call_selected', selectOption=selectOption))
return render_template('users.html')
#app.route('/<selectOption>', methods=['GET', 'POST'])
def call_selected(selectOption):
return render_template(selectOption)

Python Flask - Processing input obtained from front-end in the back-end

this is more of a question about where to find how I would do this rather than asking how to do this. I'm sure this is well covered, I'm just struggling to articulate the correct term which I could use to Google and find out the answer.
Anyway - I have a Python Flask web application. On a web page, there is an input box which requests user input. What I would like to happen, is for some magic to happen with the user input in the background. In my own scenario, I would like to take a URL, then use bs4 to pick off what I need and display this on the web page.
For simplicity, I'll ask for something for simple and I can then build on it from there: if I were to request the user to specify a number then press 'Submit', how could I multiply the number by 10?
If my code for the form was index.html:
<form class="form-horizontal" role="form" method="post" action="/">
{{ form.csrf_token }}
<fieldset>
<div class="form-group">
<label for="GetNum" class="col-lg-2 control-label">Enter Number</label>
<div class="col-lg-6">
<input type="text" id="GetNum" name="GetNum" class="form-control" value="">
</div>
<input class="btn btn-success" type="submit" value="Calculate">
</div>
</fieldset>
</form>
I noticed that I can get the input to print to a paragraph by <p>form.request.GetNum</p>.
Now for this question's example, the code for the backend functionality will be:
import math
GetNum = 10 #should be form.request.GetNum value
CalcResult = GetNum*1000
print CalcResult # or {{ CalcResult.data }} or something in index.html
My Controller (app.py) looks like:
#app.route('/', methods=['GET', 'POST'])
#login_required
def home():
error = None
form = PostForm(request.form) # unrelated to question, but will this clash?
if .. :
do something
return redirect(..)
else:
do something else..
return render_template(..)
My worry is that the home function will end up having a mass of code if I have to put the math function in there. So tl;dr, how would I implement a back end function within my code? (or please provide me with material to read, thank you!)
One other thing is I already have a form on my '/' page, will I have to rename the forms like form1 form2 because they will clash or will it be OK?
Elsewhere in your code base, either in the same file, or more likely
a module or package you could define that complicated task. Lets
create a simple module complicated.py in the same directory as your
other code, that then defines the complicated task:
def do_really_complicated_thing(info):
# lots of complicated steps
return really_complicated_data
Then in our view code, we can just use that instead of having it embedded:
from complicated import do_really_complicated_thing
#app.route('/', methods=['GET', 'POST'])
#login_required
def home():
error = None
form = PostForm(request.form)
if form.validate_on_submit() :
info = form.info.data
complicated_task = do_really_complicated_thing(info)
return render_template('something', results=complicated_task)
So, in short-- the terms you're looking for is packages and modules, they
help your code be neater and reusable.
As for clashing forms— you can just target the form to post to a specific route which just handles that form, which is much cleaner then then having to validate/parse different forms in a single route.

Categories

Resources