Some questions have arisen about the url_for() function. Basically all this does is cobble together a string of text which will be the legitimate URL of some page on your website.
To call it, you pass it two things:
- A string with the function name that you want Flask to call when this URL is clicked on (very confusingly, you don’t give it the “route” that you put in the decorator right above that function name, but rather the function name itself), and
- The key-value pairs (if any) that you want it to include as HTTP parameters in that URL, one per argument to url_for().
Example: let’s say I have this code in my routes.py:
@myapp.route("/my_route_names_are_awesome") def this_is_a_cool_func(): age = int(request.args['age']) team = request.args['team'] ... stuff ...
Then it might make sense to have this code snippet in some template (or some Python function) somewhere:
... url_for('this_is_a_cool_func', age=42, team="NY Mets") ...
If you did call that, you would get this return value:
"/my_route_names_are_awesome?age=42&team=NY+Mets"
(Note carefully that you pass 'this_is_a_cool_func' to url_for(), not 'my_route_names_are_awesome', which to me is super confusing.)
That’s really all url_for does: it formats that URL for you. You could write your own Python string function to do it if you prefer.