Flask - Dynamic URLs

Colton Allen

When I do too many dynamic URLs my stylesheets stop working. For instance. My stylesheet is in my layout.html file under /static/css/style.css

Code:

#works
@app.route('/<var1>', methods=['blah'])
def someFunc(var1):
    # code

#works
@app.route('/<var1>/<var2>', methods=['blah'])
def someNewFunc(var1, var2):
    # code

#no errors displayed but my stylesheet stops loading
@app.route('/<var1>/<var2>/<var3>', methods=['blah'])
def finalFunc(var1, var2, var3):
    # code

So I've got two questions. First, does Flask not support dynamic URLs past two? Second, is there a better way to go about this (i.e. is there a convention I should follow)?

Miguel

The problem is that your routes are ambiguous. When the browser requests your stylesheet at /static/css/style.css Flask finds two matching routes:

  • /static/<path:path> with path=css/style.css
  • /<var1>/<var2>/<var3> with var1=static, var2=css and var3=style.css

The routing algorithm used by Flask and Werkzeug prefers the longest route when multiple ones match and that makes the second one win.

The answer to this question shows a possible way to solve this problem using custom route converters.

But my recommendation is that you change your dynamic URL so that it is not so generic. You can add a fixed component to it, for example /some-prefix/<var1>/<var2>/<var3>.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related