Redirect to one Flask view from another - python

I have a view that is accessed by clicking a link on the index page. The view will perform an action and should then show the index page again. My view does that, but the url is still the url of the action view, not the index view. How can I redirect back to the index view?
#app.route('/')
def index():
return render_template('index.html')
#app.route('/u1/')
def u1():
# do something
return render_template('index.html')

Use url_for to build a url to another endpoint in the app. Use redirect to create a redirect response with that url.
from flask import url_for, redirect
#app.route('/u1/')
def u1():
# do something
return redirect(url_for('index'))

Related

Redirecting in Flask with path from url

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.

Flask - Pass argument to URL - 405 Error

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>')

How to make a page not directly accessible in Flask?

I'm developing a web application using flask microframework.
I'd like to have a view that is accessible only when it is redirected from another view and not directly from users.
To make it more clear:
#app.route('/', methods=('GET', 'POST'))
#app.route('/home', methods=('GET', 'POST'))
def home():
#Some code
return redirect(url_for('inProgress', parameter)
#app.route('/path/<parameter>')
def inProgress(parameter):
return render_template(...)
The view inProgress should be accessible only when it's "called" from the home view.
Is it possible?
Before you issue the redirect, set a flag in the session object. The "inprogress" view should check that flag. if it's set, groovy, render the page. If it's not, then redirect them to another page (and flash a warning about trying to access that page, optionally).

how do I redirect to the flask blueprint parent?

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

How To Handle Python Flask Redirect

I want to know what the best way is to serve up a redirect in Flask. I have a delete button which looks like this:
<button class="btn btn-danger btn-mini" type="button">Delete</button>
Which calls this app.route:
#app.route('/elastic_ips/<region>/delete/<ip>')
def delete_elastic_ip(region=None,ip=None):
creds = config.get_ec2_conf()
conn = connect_to_region(region, aws_access_key_id=creds['AWS_ACCESS_KEY_ID'], aws_secret_access_key=creds['AWS_SECRET_ACCESS_KEY'])
ip = ip.encode('ascii')
elis = conn.get_all_addresses(addresses=ip)
for eli in elis:
result = []
r = eli.release()
result.append(r)
return Response(json.dumps(result), mimetype='application/json')
I rather not return the result as json. I'm not sure what the "proper" way to return to the page with the delete button. Either I can put in an HTML page that just does a redirect to the refer, or is there a built in way in Flask to have return be an app.route?
Well if you want to return the url of the delete_elastic_ip, it is easy to do with url_for function (more about this function)
Don't know if this endpoint is in some blueprint, but if not, this is simple as that:
from flask import url_for, redirect
.... your code ...
return url_for('delete_elastic_ip', region=None, ip=None)
You can replace Nones also with the values you need of course :) And this will return you the url to the endpoint. Btw this is also a way to go with the urls in templates. Do not hardcode them, use url_for function in jinja templates to generate urls to the views for you. The function is available as a standart global variable in templates (more)
Also if you want just to redirect directly to some other endpoint and do not return anything, there is a function redirect in flask. Use it combined with url_for and you are good to go ;)
from flask import url_for, redirect
... your code...
return redirect(url_for('delete_elastic_ip', region=None, ip=None))
It will refresh the page, so not the best way for ajax redirect though if you want that. For ajax, just return json with the url_for result and do the stuff with it.
Here is another method using render_template
app.py code
from flask import Flask, request,render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/v_timestamp')
def v_timestamp():
return render_template('v_timestamp.html')
then can redirect to v_timestamp page. If you want this to be done via a button click event. Inside template folder, in your v_timestamp.html have this bit of code
<p align="center">v timestamp</button></p>
define button element and an a href inside the same paragraph element, in my case a href v_timestamp means v_timetsamp.html write the respective .html page you want to redirect towards.
File structure
-app.py
-templates
index.html
v_timestamp.html

Categories