I'm new to building web apps using Flask and having trouble using redirect(url_for)
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
def getSomeList(paramsFromHTML):
return someList
#app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
myData = getSomeList(paramsFromHTML)
return redirect(url_for("show_data", this_data=myData))
else:
# Show the default page for GET requests
return render_template("welcome.html")
#app.route("/show_data", methods=["GET", "POST"])
def show_data(this_data):
return render_template("show_data.html", data=this_data)
Once I get some details from HTML in my main index page, I need to route it to the show_data view function.
The function has a parameter (this_data). However, there is no parameter in the route itself - like "/show_data/<string:something>" It is just "/show_data"
I get the below error when trying this.
TypeError: show_data() missing 1 required positional argument: 'this_data'
Is it mandatory to have some kind of a parameter in the url route as well?
Is there any work around I can try for my use case?
I was able to get this working after removing the args part (this_data) from my show_data function and use the below to get the value -
this_data = request.args.get('data')
Related
I am running into a problem trying to redirect in Flask using the following:
#views.route('/dash_monitoring/<path:url>')
#login_required
def monitoring_page(url):
return redirect("/home/dash_monitoring/{}".format(url))
The url in <path:url> is in the format https://somesite.com/detail/?id=2102603 but when I try to print it in the function, it prints https://somesite.com/detail only without the id part,so it obviously redirects to /home/dash_monitoring/https://somesite.com/detail instead of /home/dash_monitoring/https://somesite.com/detail/?id=2102603.
What should I do so it keeps the id part and redirects to the right url?
You can use request.url and imply string manipulation:
#views.route('/dash_monitoring/<path:url>')
#login_required
def monitoring_page(url):
parsed_path = request.url.split('/dash_monitoring/')[1]
#return the parsed path
return redirect("/home/dash_monitoring/{}".format(parsed_path))
Alternatively, you can iterate through request.args for creating query string and construct path with args
#views.route('/dash_monitoring/<path:url>')
#login_required
def monitoring_page(url):
query_string = ''
for arg,value in request.args.items():
query_string+=f"{arg}={value}&"
query_string=query_string[:-1] # to remove & at the end
path=f"{path}?{query_string}"
#return the parsed path
return redirect(f"/home/dash_monitoring/{path}")
I hope this helps :)
This has an easy solution, we use the url_for function:
from flask import Flask, redirect, url_for
app = Flask(__name__)
#app.route('/<name>')
def index(name):
return f"Hello {name}!"
#app.route('/admin')
def admin():
return redirect(url_for('index',name = 'John'))
if __name__ == '__main__':
app.run(debug = True)
In my code we firs import redirect and url_for.
We create 2 routes index and admin.
In index route we output a simple response with the named passed to the url. So if we get example.com/John it will output Hello John!.
In admin route we redirect the user to index route because it's not the admin (This is a simple example that can you can model with what you want). The index route needs a name so we pass inside the url_for function some context so it can desplay the name.
I am very new to Flask and Web development so sorry in advanced if I use incorrect terms.
I am trying to create a webpage using Python and Flask. To do so, I have the following:
from flask import Flask, request, render_template, redirect, url_for
from flask_assets import Environment, Bundle
app = Flask(__name__)
assets = Environment(app)
#app.route("/", methods=["GET", "POST"])
def login():
# Code to do the login
error = None
if request.method == 'POST':
# code checking the passwords. if correct:
return render_template('index.html')
# else:
# error
return render_template('login.html', error = error)
What this snippet of code does is to load the login.html where the user is asked to put an username and password and after checking if they are the ones expected, it loads index.html where the user can upload his or her data. Once the data is submitted a new function is called:
#app.route('/transform', methods=["POST"])
def transform():
f = request.files['data_file']
if not f:
return "No file"
# code
return render_template('message.html')
The problem is that while in local the message.html gets display once transform has finished, in the server it doesn't appear although the function eventually does what it's expected to do. The other two templates are correctly displayed both in local and in the server. Could it be due to be in a different route?
The index.html is defined with action='\transform', in case it may give a hint.
Any idea of why could this be happening?
I have an application build with flask and I want to pass one input tag from my current html view ('/setpickup') to another view, in order to reuse the variable values of that input and print them again in the new view ('/payments.html'). But I dont know if it is possible, thanks you. Here is a brief of the code that is not working at this moment.
#app.route('/')
#app.route('/setpickup', methods=['GET', 'POST'])
#login_required
def setpickup():
form = RideForm()
device = Utils.getDevice()
if request.method == 'POST':
data_input_data = form.data_input.data
return redirect(url_for('payment', data_input_data=data_input_data))
#app.route('/payment')
#login_required
def payment(data_input_data):
device = Utils.getDevice()
return render_template("/"+device+"/payment.html",
device=device,
data_input_data=data_input_data)
I am learning Flask and I am having some trouble passing arguments to a URL for use on another page. For example, I have a form on /index and I would like it to redirect to a /results page where I could print the form data. My attempt is this:
from flask import render_template
from flask import redirect
from flask import url_for
from app import app
from .forms import LoginForm
#app.route('/')
#app.route('/index', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
name = form.artistName.data
return redirect(url_for('result', name=name))
else:
return redirect('/index')
return render_template('index.html',
title='Sign In',
form=form)
#app.route('/result/<name>')
def result(name):
return render_template('results.html')
I receive a 405 error Method not allowed for the requested URL when redirecting to the /results page. I would like to construct a URL on /results using the result of the form as an argument.
How can I do this? Many thanks
you defined
#app.route('/result/<name>')
which means its default http method is GET;
when this runs:
if form.validate_on_submit():
# POST method
name = form.artistName.data
# redirect Will use 'POST'
return redirect(url_for('result', name=name))
so , you got Method not allowed for the requested URL.
i think you can add a POST method to #app.route('/result/<name>')
Is it possible to rewrite a URL with Flask e.g. if a POST request is received via this route:
#app.route('/', methods=['GET','POST'])
def main():
if request.method == 'POST':
#TODO: rewrite url to something like '/message'
return render_template('message.html')
else:
return render_template('index.html')
I'm aware I can use a redirect and setup another route but I prefer to simply modify the url if possible.
You can call your route endpoint functions from another routes:
# The “target” route:
#route('/foo')
def foo():
return render_template(...)
# The rewrited route:
#route('/bar')
def bar():
return foo()
You can even access g etc. This approach can be also used when the Flask's routing facilities cannot do something that you want to implement.
This is actual solution to this problem (but maybe a dirty hack):
def rewrite(url):
view_func, view_args = app.create_url_adapter(request).match(url)
return app.view_functions[view_func](**view_args)
We invoke the URL dispatcher and call the view function.
Usage:
#app.route('/bar')
def the_rewritten_one():
return rewrite('/foo')
I think you could be interested in redirect behavior
from flask import Flask,redirect
then use
redirect("http://www.example.com", code=302)
see: Redirecting to URL in Flask
from flask import Flask, redirect, url_for
app = Flask(__name__)
#app.route("/")
def home():
return "hello"
#app.route("/admin"):
def admin():
return redirect(url_for("#name of function for page you want to go to"))