I currently have my site like this:
#main.route("/reports", methods=["GET", "POST"])
def reports():
return render_template(
"template.html")
I intend to add a new design and place it in the following way if in the url they add "/reports/1" or "/reports/0" direct them to a different template:
#main.route("/reports/<int:ds>", methods=["GET", "POST"])
def reports(ds):
View=ds
if View == 1:
return render_template("template.html")
if View == 0:
return render_template("templateNew.html")
Within templeteNew.html I have the option to return to my old layout and place it in the same way by sending a parameter
<a href="{{ url_for('main.report_in', ds=1) }}" >
Return to previous layout
</a>
The problem is that in the whole project and in external projects it refers to this url:
127.0.0.1:8000/reportes
and it might cause errors if I implement it the way I intended. What I want is that if there is any other way to condition the url, if they write this url:
http://127.0.0.1:8000/reportes
I directed them to this:
#main.route("/reports/<int:ds>", methods=["GET", "POST"])
def reports(ds):
View=ds
if View == 1:
return render_template(
"template.html")
if View == 0:
return render_template(
"templateNew.html")
Any suggestions to improve this please?
http://127.0.0.1:8000/reportes looks like a typo (extra "e").
Anyway you can add one more route to your function as follows:
#main.route("/reports", methods=["GET", "POST"])
#main.route("/reports/<int:ds>", methods=["GET", "POST"])
def reports(ds=1): # <-- provide here the default value you want ds to be
View=ds
if View == 1:
return render_template(
"template.html")
if View == 0:
return render_template(
"templateNew.html")
Another option is to pass the default value in the route definition:
#main.route("/reports", methods=["GET", "POST"], defaults={'ds': 1})
#main.route("/reports/<int:ds>", methods=["GET", "POST"])
def reports(ds): to be
View=ds
if View == 1:
return render_template(
"template.html")
if View == 0:
return render_template(
"templateNew.html")
Related
#app.route('/predict', methods=['GET', 'POST'])
def predict1():
# radio = 0
if request.method == 'POST':
value = request.get_json()
if(value['radioValue'] == 'word'):
radio = 0
return "ok"
elif(value['radioValue'] == 'sentence'):
radio = 1
return "ok"
else:
if(radio==0):
lists = ["my","word"]
elif(radio==1):
lists = ["my","sentence"]
return jsonify({'prediction': lists})
Hello, I am new to Flask and web development. So, here is my question, I am getting two radio button value named word and sentence. I want to pass lists = ["my","word"] if value is word else lists = ["my","sentence"].
But here jsonify() is not returning anything. So what am I doing wrong here?
Though it return lists if I declare radio variable outside if-else block as you can see I commented them out.
Also if I don't return anything inside post what I did as return "ok" it doesn't return anything even if I declare radio = 0 or 1 outside if-else block.
A short explanation will be really helpful.
If you check your debug log, you will probably see a NameError where radio is not defined. This is due to radio being a local variable, and not a session variable as you probably intended.
To store variables for further usage in Flask, you need to use sessions.
from flask import session
#app.route('/predict', methods=['GET', 'POST'])
def predict1():
if request.method == 'POST':
value = request.get_json()
if(value['radioValue'] == 'word'):
session["radio"] = 0
return "ok"
elif(value['radioValue'] == 'sentence'):
session["radio"] = 1
return "ok"
else:
if(session["radio"]==0):
lists = ["my","word"]
elif(session["radio"]==1):
lists = ["my","sentence"]
return jsonify({'prediction': lists})
I have created a function that returns a list a list of scores. now I want that list to be used in another function
here is my app.py file
#app.route('/getmarks', methods=['GET', 'POST'])
def getmarks():
if request.method == 'POST':
marks = list(map(float,(request.form['score']).split()))
return render_template('results.html', marks=marks)
return render_template('getmarks.html')
#app.route('/displaygraph/marks', methods=['GET', 'POST'])
def displaygraph(marks):
return render_template('graphs.html', marks=marks)
How do I get that marks list in my displaygraph function?
I am trying to pass a variable from one route to another, but I am unable to. Can someone guide me on doing it? I get the error on the last line.
#app.route("/search", methods=['GET', 'POST'])
def search():
if request.method == 'GET':
return render_template('search.html', navbar=True)
else:
query = request.form.get('query').lower()
query_like = '%' + query + '%'
books = db.execute('SELECT * FROM books WHERE (LOWER(isbn) LIKE :query) OR (LOWER(title) LIKE :query) '
'OR (LOWER(author) LIKE :query)',
{'query': query_like}).fetchall()
if not books:
return render_template('error.html', message='No Books were Found!', navbar=True)
return render_template('books.html', query=query, books=books, navbar=True)
#app.route("/books", methods=['GET', 'POST'])
def books():
return render_template('books.html', query=query, books=books)
The problem is the way your code is organized. Variables in a function are scoped within the function, so books isn't available from the second route. In addition to that, you have a naming collision where books=books is referring to the function itself (which is defined at the module scope).
If you want to share code between routes, put it in a separate function:
def get_books(query, show_nav_bar=False):
query = query.lower()
query_like = '%' + query + '%'
books = db.execute('SELECT * FROM books WHERE (LOWER(isbn) LIKE :query) OR (LOWER(title) LIKE :query) '
'OR (LOWER(author) LIKE :query)', {'query': query_like}).fetchall()
if not books:
return render_template('error.html', message='No Books were Found!', navbar=True)
return render_template('books.html', query=query, books=books, navbar=show_nav_bar)
#app.route("/search", methods=['GET', 'POST'])
def search():
if request.method == 'GET':
return render_template('search.html', navbar=True)
else:
return get_books(request.form.get('query'), show_nav_bar=True)
#app.route("/books", methods=['GET', 'POST'])
def books():
return get_books(request.form.get('query'))
I am trying to pass params to the URL in flask, but I can not get them to show up for anything.
#logout.route('/logout')
def logout_page():
current_provider = current_oauth_user.get_provider()
return render_template('index.html', provider=current_provider)
I expect to see /logout?provider=facebook but I just get /logout
Right now I am doing this:
#logout.route('/logout')
def logout_page():
provider = request.args.get('provider')
current_provider = current_oauth_user.get_provider()
if not provider and current_provider:
return redirect(url_for('logout.logout_page',
provider=current_provider))
return render_template('index.html')
but that just seems so terrible.
You should return some value using '/logout' path.
So at first, you use render_template(index.html) under def main(). Then you create def logout_page() and return some value ( in your case is current_provider).
#app.route('/')
def main():
return render_template('index.html')
#app.route('/logout')
def logout_page():
current_provider = current_oauth_user.get_provider()
return current_provider
if __name__=="__main__":
app.run(port=8000)
I have got a few subpages which look very similiar:
They are almost the same but each of them presents different currency:
#app.route('/', methods=['POST', 'GET'])
#app.route('/dollar', methods=['POST', 'GET'])
def dollar_page():
form = MyTextForm()
if form.validate_on_submit():
values = app.process(request.form["values"])
labels = get_data()
return render_template('currency.html', currency="dollar", labels=labels, values=values)
#app.route('/euro', methods=['POST', 'GET'])
def euro_page():
form = MyTextForm()
sentiment = ""
if form.validate_on_submit():
values = app.process(request.form["values"])
labels = get_data()
return render_template('currency.html', currency="euro", labels=labels, values=values)
#app.route('/pound', methods=['POST', 'GET'])
def pound_page():
... etc ...
What is the best way to get rid of this duplication in Flask applications? Is there any pattern? Thanks!
Create a variable in your route to receive the type of currency. The route variable is passed as an argument to the view function. The / route doen't have the variable, so provide a default in that case.
import functools
def verify_currency(f):
#functools.wraps(f)
def wrapper(currency_type):
if currency_type not in ['dollars', 'euros']: #can add more currencies to list later
return flask.render_template("error.html") #or redirect
return f(currency_type)
return wrapper
#app.route('/', methods=['POST', 'GET'], defaults={'currency': 'euro'})
#app.route('/currency/<currency>', methods=['POST', 'GET'])
#verify_currency
def dollar_page(currency):
form = MyTextForm()
values = labels = None
if form.validate_on_submit():
values = app.process(request.form["values"])
labels = get_data()
return render_template('currency.html', currency=currency, labels=labels, values=values)