Flask routing tricks

by sethtrain

While working on a project today I wondered how I might complete this particular task.  I needed user profiles. Each profile was going to require an extra form field or two and I wanted to have different urls but the same “view”.  So I am going to show what I did to solve my problem.

Since Flask routing is just a decorator, you can add as many decorators as you want to the view function:

users = Module(__name__, name="users", url_prefix="")

@users.route("/affiliates/new")
@users.route("/users/new")
def new():
    form = RegistrationForm()
    return render_template("users/new.html", form=form)

The route() function just passes keyword args onto werkzeug.routing.Rule which accepts a dictionary called defaults. As you would think, defaults sets default values to variables accepted by the view function. So I decided to use the defaults dictionary to set the value for profile_type. This will never be overwritten since I am not accepting profile_type as a url parameter.

users = Module(__name__, name="users", url_prefix="")

@users.route("/affiliates/new",
             defaults={'profile_type': 'affiliates'})
@users.route("/users/new",
             defaults={'profile_type': 'sales'})
def new(profile_type=None):
    # Handle form with profile_type variable...
    return render_template("users/new.html", form=form)

This might be a little hackish but it works like I thought it would.