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:

<a href="/elastic_ips/{{region}}/delete/{{eli['public_ip']}}"><button class="btn btn-danger btn-mini" type="button">Delete</button></a>

Which calls this app.route:

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()
        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?

12/6/2012 5:50:22 AM

Accepted Answer

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.

12/6/2012 7:17:57 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow