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.
Related
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')
I want to define multiple endpoints that render different templates, without writing out each one. The endpoints are all similar, one looks like:
#app.route('/dashboard/')
def dashboard():
return render_template('endpoints/dashboard.html')
I tried defining a function in a for loop for each endpoint name, but the problem is that the name of the function stays the same and Flask raises an error about that.
routes = ['dashboard', 'messages', 'profile', 'misc']
for route in routes:
#app.route('/' + route + '/')
def route():
return render_template('endpoints/' + route + '.html')
How can I create these views without repeating myself?
You don't want to do this. Instead, use a variable in the route to capture the template name, try to render the template, and return a 404 error if the template doesn't exist.
from flask import render_template, abort
from jinja2 import TemplateNotFound
#app.route('/<page>/')
def render_page(page):
try:
return render_template('endpoints/{}.html'.format(page))
except TemplateNotFound:
abort(404)
Alternatively, and less preferably, you can use the same function name as long as you provide Flask with unique endpoint names. The default name is the name of the function, which is why Flask complains.
for name in routes:
#app.route('/', endpoint=name)
def page():
return render_template('endpoints/{}.html'.format(name))
I'm trying to add another view to my Flask app. My app/views.py looks like this:
from flask import render_template
from app import app
from helpfulFunctions import *
def getRankingList():
allPlayers = main()
return allPlayers
def displayLimitedNumberOfPlayers(limit):
allPlayers = main()
allPlayers[0] = limitPlayers(allPlayers[0], limit)
allPlayers[1] = limitPlayers(allPlayers[1], limit)
return allPlayers
#app.route("/")
#app.route("/index")
def index():
rankingList = getRankingList()
return render_template('index.html', title='Home', rankingList = rankingList)
#app.route("/top100")
def top100():
rankingList = displayLimitedNumberOfPlayers(100)
return render_template('top100.html', rankingList = rankingList)
if __name__ == '__main__':
app.run(debug=True)
I've tried to mimic how the Miguel Grinberg tutorial defines routes for / and for /index. I've created a view called top100.html in my templates folder, where the "index.html" file also lives. However, when I try to hit localhost:5000/top100.html, I get:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
So it seems like Flask doesn't think that URL has a view associated with it...but I'm not sure why.
Any idea?
Thanks for the help,
bclayman
There is no view top100.html in your code.You can do either of these
localhost:5000/top100
OR
change #app.route("/top100") to #app.route("/top100.html")
The route (or url) is specified in the #app.route() definition, so you should visit localhost:5000/top100.
The render_template top100.html is only referenced internally within Flask to specify the template used. Really, this page could be named anything and does not have to be named in any similar way to the route...it just has to match the template file used to build the page served at that url.
I have some problem with redirecting with anchors from python code.
My code:
func():
...
redirect(url_for('my_view', param=param, _anchor='my_anchor'))
This redirect didn't redirect me to #my_anchor.
In template link like:
works good... May be problem in flask function "redirect".
How I can use redirect with anchors in Flask?
Flask version 0.10.x
if your goal is to be redirected to a page with an anchor preselected in the url I think the problem may be connected to the function you have passed in the 'url_for'. Below is my attempt to do what you described.
views.py
from flask import Flask
from flask import redirect, url_for
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
#app.route('/myredirect')
def my_redirect():
return redirect(url_for('hello_world',_anchor='my_anchor'))
if __name__ == '__main__':
app.run()
This does not need a template, as as soon as you hit /myredirect you are redirected to / with anchor #my_anchor
After you get your views started with $ python views.py and navigate to http://127.0.0.1:5000/myredirect you end up on http://127.0.0.1:5000/#my_anchor
A short and simple way of doing this is
return redirect(url_for('hello_world') + '#my_anchor')
instead of
return redirect(url_for('hello_world',_anchor='my_anchor'))
which works because url_for returns a string for the endpoint.
Suppose i have the following structure:
/root/user/login
I do the login in a blueprint:
app.register_blueprint(login_blueprint,url_prefix=prefix('/user'))
I can redirect to ".index":
#login_blueprint.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
#### this redirects me to '/root/user/'
redirect_to_index= redirect(url_for('.index'))
response = current_app.make_response(redirect_to_index)
# do the log in
return response
redirect_to_index=redirect(url_for('.index'))
response = current_app.make_response(redirect_to_index)
The redirect brings me to /root/user:
redirect(url_for('.index'))
But how to get to /root (which is up relative to the current url (..)?
You can pass url_for the name of the endpoint function for /root/.
For example, if you have:
#app.route('/root/')
def rootindex():
return "this is the index for the whole site."
elsewhere in your app, you can do:
redirect(url_for('rootindex'))
To cause a redirect here. When you put a . in front of the string you pass to url_for, that tells it to look for an endpoint in the current blueprint. By leaving the . off, you tell it to look for a endpoint in the app