How do I use url_for if my method has multiple route annotations?

2024/11/19 7:41:38

So I have a method that is accessible by multiple routes:

@app.route("/canonical/path/")
@app.route("/alternate/path/")
def foo():return "hi!"

Now, how can I call url_for("foo") and know that I will get the first route?

Answer

Ok. It took some delving into the werkzeug.routing and flask.helpers.url_for code, but I've figured out. You just change the endpoint for the route (in other words, you name your route)

@app.route("/canonical/path/", endpoint="foo-canonical")
@app.route("/alternate/path/")
def foo():return "hi!"@app.route("/wheee")
def bar():return "canonical path is %s, alternative is %s" % (url_for("foo-canonical"), url_for("foo"))

will produce

canonical path is /canonical/path/, alternative is /alternate/path/

There is a drawback of this approach. Flask always binds the last defined route to the endpoint defined implicitly (foo in your code). Guess what happens if you redefine the endpoint? All your url_for('old_endpoint') will throw werkzeug.routing.BuildError. So, I guess the right solution for the whole issue is defining canonical path the last and name alternative:

""" since url_for('foo') will be used for canonical pathwe don't have other options rather then defining an endpoint foralternative path, so we can use it with url_for
"""
@app.route('/alternative/path', endpoint='foo-alternative')
""" we dont wanna mess with the endpoint here - we want url_for('foo') to be pointing to the canonical path
"""
@app.route('/canonical/path') 
def foo():pass@app.route('/wheee')
def bar():return "canonical path is %s, alternative is %s" % (url_for("foo"), url_for("foo-alternative"))
https://en.xdnf.cn/q/26462.html

Related Q&A

Shortest Python Quine?

Python 2.x (30 bytes): _=_=%r;print _%%_;print _%_Python 3.x (32 bytes) _=_=%r;print(_%%_);print(_%_)Is this the shortest possible Python quine, or can it be done better? This one seems to improve o…

How to find all python installations on mac os x and uninstall all but the native OS X installation

I have installed a few versions on my MacBook for different projects and have only now realized what a mistake that was. I have used homebrew to install it, installed it via pythons website (Python 2.7…

Who runs the callback when using apply_async method of a multiprocessing pool?

Im trying to understand a little bit of whats going on behind the scenes when using the apply_sync method of a multiprocessing pool. Who runs the callback method? Is it the main process that called ap…

Difference between hash() and id()

I have two user-defined objects, say a and b. Both these objects have the same hash values. However, the id(a) and id(b) are unequal.Moreover, >>> a is b False >>> a == b TrueFrom th…

get class name for empty queryset in django

I have empty queryset of model Studentstudents = Students.objects.all()If the above queryset is empty, then how can i get the model(class name)?How can i get the model name for empty queryset?EDIT:Ho…

`Sudo pip install matplotlib` fails to find freetype headers. [OS X Mavericks / 10.9] [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about a specific programming problem, a software algorithm, or s…

Parallel processing from a command queue on Linux (bash, python, ruby... whatever)

I have a list/queue of 200 commands that I need to run in a shell on a Linux server. I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few secon…

How do I select and store columns greater than a number in pandas? [duplicate]

This question already has answers here:How do I select rows from a DataFrame based on column values?(17 answers)Closed 28 days ago.I have a pandas DataFrame with a column of integers. I want the rows …

Plotting transparent histogram with non transparent edge

I am plotting a histogram, and I have three datasets which I want to plot together, each one with different colours and linetype (dashed, dotted, etc). I am also giving some transparency, in order to s…

Cross-platform desktop notifier in Python

I am looking for Growl-like, Windows balloon-tip-like notifications library in Python. Imagine writing code like:>>> import desktopnotifier as dn >>> dn.notify(Title, Long description…